WPF ListView控件绑定的ItemsSource在XAML [英] WPF ListView Binding ItemsSource in XAML
问题描述
我有它一个ListView一个简单的XAML页面这样定义
I have a simple XAML page with a ListView on it defined like this
<ListView Margin="10" Name="lvUsers" ItemsSource="{Binding People}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
<GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
</GridView>
</ListView.View>
</ListView>
在code后面我做的: -
In the code behind I do:-
public ObservableCollection<Person> People { get; set; }
public ListView()
{
InitializeComponent();
this.People = new ObservableCollection<Person>();
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在code的背后是这样
If I set the ItemsSource of my listview in the code behind like this
lvUsers.ItemsSource = this.People;
它的工作原理,并如预期的那样显示我的网格
it works and my grid is displayed as expected
但是,如果我删除了这一行,并尝试在XAML绑定
However if I remove that line and try and bind in the XAML
<ListView Margin="10" Name="lvUsers" ItemsSource="{Binding People}">
它不再起作用。
it no longer works.
为什么没有在XAML工作结合?
Why doesn't the binding in the XAML work?
推荐答案
如果你不这样做已经在XAML例如,你需要设置的DataContext
的你的绑定。此外,由于人
属性不落实 INotifyPropertyChanged的
您可能希望创建之前的InitializeComponent <这个名单/ code>,在最起码你之前设置
的DataContext
,可以肯定列表准备绑定计算时。您可以添加到您的的ObservableCollection
后,但如果你不通知用户界面,它不会工作在该点之后创建
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" });
}
这篇关于WPF ListView控件绑定的ItemsSource在XAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!