XAML中的WPF ListView绑定ItemsSource
我有一个简单的XAML页面,其上有一个像这样定义的ListView
在我做的代码中: –
public ObservableCollection People { get; set; } public ListView() { InitializeComponent(); this.People = new ObservableCollection(); 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" }); }
如果我在后面的代码中设置listview的ItemsSource,就像这样
lvUsers.ItemsSource = this.People;
它工作,我的网格按预期显示
但是,如果我删除该行并尝试绑定XAML
它不再有效。
为什么XAML中的绑定不起作用?
如果您还没有这样做,例如在XAML中,您需要为绑定设置DataContext
。 此外,由于People
属性未实现INotifyPropertyChanged
您可能希望在InitializeComponent
之前创建此列表,至少在设置DataContext
之前,确保在评估绑定时列表已准备就绪。 您可以稍后添加到ObservableCollection
但如果您在该点之后创建它而不通知UI它将无法工作
public ListView() { this.People = new ObservableCollection(); 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" }); }
将此行放在xaml.cs中的现有代码之后
this.DataContext = People;
并用你的xaml替换
ItemsSource="{Binding People}"
至
ItemsSource="{Binding}"