【发布时间】:2015-11-22 07:58:31
【问题描述】:
我正在尝试在 List 和 DataGrid 之间创建绑定。我还没有在网上找到一个很奇怪的有效解决方案。
在我的小例子中,我使用两个 public 属性 Age 和 Name 创建了一个 List 对象:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
public ObservableCollection<Person> Collection { get; set; }
public List<Person> Persons { get; set; }
private void WindowLoaded(object sender, RoutedEventArgs e)
{
this.Persons = new List<Person>();
for (int i = 0; i != 35; i++)
{
this.Persons.Add(new Person() {Age = i, Name = i.ToString()});
}
this.Collection = new ObservableCollection<Person>(this.Persons);
}
XAML 代码如下所示:
<Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
<DataGrid x:Name="DataGrid" ItemsSource="{Binding Collection}" />
</Grid>
或者这个(两者都不起作用):
<Grid DataContext="{Binding ElementName=TestWindow, Path=.}">
<DataGrid x:Name="DataGrid" ItemsSource="{Binding Persons}" />
</Grid>
如果我使用this.DataGrid.ItemsSource = this.Persons;,我至少会看到列表中的所有项目,但每次源List 发生变化时我都必须this.DataGrid.Items.Refresh(),这就是我问这个问题的原因:
我做错了什么?我需要实现INotifyPropertyChanged吗?
这个问题一定很容易回答,但如果能理解其中的机制也很棒。
【问题讨论】: