2016-04-12 67 views
0

我想從代碼端填充我的頁面。 我的頁面XAML代碼是在這裏:UWP不從代碼加載UI數據

<Hub x:Name="MainPageHub" Grid.Row="1" > 
        <HubSection x:Name="HomeHub" Header="Home" DataContext="{x:Bind m_people, Mode=OneWay}"> 
         <DataTemplate> 
          <GridView x:Name="PeopleGrid" ItemsSource="{Binding Mode=OneWay}"> 
           <GridView.ItemTemplate> 
            <DataTemplate x:DataType="data:PeopleViewModel"> 
             <StackPanel Background="DarkGray" HorizontalAlignment="Left" Margin="6" Orientation="Horizontal"> 
              <Image Width="50" Height="50" Source="{x:Bind PictureUrl, Mode=OneWay}"/> 
              <TextBlock FontSize="15" Text="{x:Bind Happening, Mode=OneWay}"/> 
             </StackPanel> 
            </DataTemplate> 
           </GridView.ItemTemplate> 
           <GridView.ItemsPanel> 
            <ItemsPanelTemplate> 
             <ItemsWrapGrid MaximumRowsOrColumns="2" Orientation="Horizontal"></ItemsWrapGrid> 
            </ItemsPanelTemplate> 
           </GridView.ItemsPanel> 
          </GridView> 
         </DataTemplate> 
        </HubSection> 
        </Hub> 

我嘗試了Loaded事件做到這一點,但的ObservableCollection不更新UI。 MainPage.xaml.cs中:

public sealed partial class MainPage : Page 
    { 
     private ObservableCollection<PeopleViewModel> m_people { get; set;} 

     public MainPage() 
     { 
      this.InitializeComponent(); 
      this.Loaded += Page_Loaded; 
     } 

     private void Page_Loaded(object sender, RoutedEventArgs e) 
     { 
      m_people = new ObservableCollection<PeopleViewModel>(); 
      m_people.Add(new PeopleViewModel {Happening = "vaalam", DateTime = DateTime.Now, PictureUrl = "Assets/Data/Picture/1.png"}); 
      m_people.Add(new PeopleViewModel {Happening = "vaalam", DateTime = DateTime.Now, PictureUrl = "Assets/Data/Picture/2.png" }); 
      m_people.Add(new PeopleViewModel {Happening = "vaalam", DateTime = DateTime.Now, PictureUrl = "Assets/Data/Picture/3.png" }); 
     } 

但是,當我填的是m_people集合中的MainPage(),它的工作原理。爲什麼不Page_Loaded工作?

+0

當您在initializecomponent之後添加事件偵聽器時,它可能不會調用Page_load函數,因爲該頁面在事件初始化時已被加載 –

+0

我試圖切換這兩行,但它沒有工作 – Tudnor

回答

0

我找到了答案!問題是private ObservableCollection<PeopleViewModel> m_people { get; set;}

我不得不改變private ObservableCollection<PeopleViewModel> m_people = new ObservableCollection<PeopleViewModel>();

對不起,這種不必要的問題!