若要实现自定义的数据结构如类、结构体等数据对象与UI界面上的控件进行绑定,主要的是要对数据结构对象实现 INotifyPropertyChanged 接口。如果没有实现,即使是双向绑定也无法完成绑定想要的效果;
若要实现 INotifyPropertyChanged,需要声明 PropertyChanged 事件并创建 OnPropertyChanged 方法。 然后,对于每个需要更改通知的属性,只要进行了更新,就可以调用 OnPropertyChanged。
using System.ComponentModel;
namespace SDKSample
{
public class Person : INotifyPropertyChanged
{
private string name;
public event PropertyChangedEventHandler PropertyChanged;
public Person()
{
}
public Person(string value)
{
this.name = value;
}
public string PersonName
{
get { return name; }
set
{
name = value;
OnPropertyChanged("PersonName");//只有使用此才能完成修改Person对象的PersonName值UI对应刷新的效果;
}
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
}