上篇文章说到,简单binding只能反映List的Add和Remove操作。如果想要所有变化显示出来,必须使用ObservableCollection来代替List,同时把类继承于INotifyPropertyChanged来让控件了解到Collection中每个对象的属性发生变化。
首先在Main.cs里把List改成ObservableCollection。
// Main.cs
using System.Collections.ObjectModel;
public ObservableCollections<Item> Items{get;set;}
...
然后改动类的代码,我这里只改动了IsChecked属性相关代码,其他属性类推:
// Item.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class Item : INotifyPropertyChanged
{
private bool _IsChecked;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public bool IsChecked
{
get
{
return _IsChecked;
}
set
{
if (_IsChecked != value)
{
_IsChecked = value;
NotifyPropertyChanged();
}
}
}
}
}
然后在Xaml里对PropertyChanged进行监听(同样地可以扩展到其他属性的binding上面)
<!-- Main.xaml -->
<CheckBox IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged}"/>
这样完成以后,所有ObservableCollection中元素只要有一个属性有改变对应的显示便也都会改变。
binding还有不同模式。不同模式的用处详见这个链接。