最近使用WPF访问SQL数据库,第一次使用到InotifyPropertyChanged接口,感觉它特别好用,学习到一些东西。附上部分是实现代码。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
///<summary>
///创建Student类 实现InotifyPropertyChanged接口
///</summary>
namespace InterfaceWpf
{
publicclassStudent : INotifyPropertyChanged
{
publicstringstuname;
public stringstuID;
publicDateTime stubirth;
publicstringstusex;
publicstringstuaddress;
publicstringStuname
{
get{ return stuname; }
set
{
if (value!= stuname)
{
stuname = value;
NotifyPropertyChanged("Stuname");
}
}
}
publicstringStuID
{
get{ return stuID; }
set
{
if (value!= stuID)
{
stuID = value;
NotifyPropertyChanged("StuID");
}
}
}
publiceventPropertyChangedEventHandler PropertyChanged;
publicvoidNotifyPropertyChanged(stringpropertyName)
{
if(PropertyChanged != null)
{
PropertyChanged(this, newPropertyChangedEventArgs(propertyName));
}
}
}
}
说明1:ObserableCollection<T>类 (T表示Object,可以为任何类型)
表示一个动态数据集合,在添加项、移除项或刷新整个列表时,此集合将提供通知。用时在main方法里实例化对象。
说明2:INotifyPropertyChanged接口
为了完全支持将绑定源对象中的数据值传送到绑定目标,在支持可绑定属性的集合中的每个对象都必须实现适当的属性更改通知机制,如 INotifyPropertyChanged 接口
WPF 提供 ObservableCollection<T> 类,它是实现 INotifyCollectionChanged 接口的数据集合的内置实现
说明3:PropertyChanged事件
当属性值发生更改时触发事件