WPF ListView Binding ItemsSource in XAML

前端 未结 2 1787
暗喜
暗喜 2021-01-01 14:57

I have a simple XAML page with a ListView on it defined like this


    
  • 相关标签:
    2条回答
    • 2021-01-01 15:52

      If you don't do it already, in XAML for example, you need to set DataContext for your binding. Also since People property does not implement INotifyPropertyChanged you might want to create this list before InitializeComponent, at very least before you set DataContext, to be sure list is ready when binding is evaluated. You can add to your ObservableCollection later but if you create it after that point without notifying UI it won't work

      public ListView()
      {
          this.People = new ObservableCollection<Person>();
          InitializeComponent();
          this.DataContext = this;
      
          this.People.Add(new Person() { Name = "John Doe", Age = 42, Mail = "john@doe-family.com" });
          this.People.Add(new Person() { Name = "Jane Doe", Age = 39, Mail = "jane@doe-family.com" });
          this.People.Add(new Person() { Name = "Sammy Doe", Age = 7, Mail = "sammy.doe@gmail.com" }); 
      }
      
      0 讨论(0)
    • 2021-01-01 15:57

      Put this line after the existing code in xaml.cs

      this.DataContext = People;
      

      and replace your xaml with

      ItemsSource="{Binding People}" 
      

      to

      ItemsSource="{Binding}"
      
      0 讨论(0)
    提交回复
    热议问题