ropertyChangedBase 是实现 INotifyPropertyChanged 的类型的基类,它提供了用于引发 PropertyChanged 通知的方法。
引发通知
有多种方法可以引发 PropertyChanged 通知,具体取决于您要执行的操作。
最常见的情况是让属性在每次分配到时引发通知。PropertyChangedBase提供了一个很好的实用程序方法来提供帮助:SetAndNotify。通过引用,它需要一个字段和一个要分配给该字段的值。如果字段的值 != 该值,则进行分配,并引发属性已更改通知。例如:
class MyClass : PropertyChangedBase
{
private string _name;
public string Name
{
get { return this._name; }
set { SetAndNotify(ref this._name, value); }
}
要连接到对象,必须放入视图中:
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/>
如果要为当前属性以外的属性引发 PropertyChanged 通知,可以使用NotifyOfPropertyChange方法。如下所示:
class MyClass : PropertyChangedBase
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
private set
{
SetAndNotify(ref _firstName, value);
// Preferred if you're using C# 6, as it provides compile-time safety
this.NotifyOfPropertyChange(nameof(this.FullName));
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
private set
{
SetAndNotify(ref _lastName, value);
// Preferred for C# 5 and below, as it provides compile-time safety
this.NotifyOfPropertyChange(() => this.FullName);
}
}
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
您还可以在构造函数中将内容连接在一起,如下所示:
class MyClass : PropertyChangedBase
{
private string _firstName, _lastName;
public MyClass()
{
this.Bind(s => s.FirstName, (o, e) => NotifyOfPropertyChange(nameof(FullName)));
this.Bind(s => s.LastName, (o, e) => NotifyOfPropertyChange(nameof(FullName)));
}
public string FirstName
{
get { return _firstName; }
private set { SetAndNotify(ref _firstName, value); }
}
public string LastName
{
get { return _lastName; }
private set { SetAndNotify(ref _lastName, value); }
}
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
与 PropertyChanged.Fody 一起使用
PropertyChanged.Fody是一个很棒的包,它在编译时注入代码以自动为您的属性引发PropertyChanged通知,从而允许您编写非常简洁的代码。它还将找出属性之间的依赖关系,并适当地引发通知,例如:
class MyClass : PropertyChangedBase
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public string FullName { get { return String.Format("{0} {1}", this.FirstName, this.LastName); } }
public void SomeMethod()
{
// PropertyChanged notifications are automatically raised for both FirstName and FullName
this.FirstName = "Fred";
}