有人知道BindableBase现在是否仍然可用,或者我们应该坚持使用INotifyChanged事件吗?看起来BindableBase很快就失去了它的光泽。感谢您能提供的任何信息。
有人知道BindableBase现在是否仍然可用,或者我们应该坚持使用INotifyChanged事件吗?看起来BindableBase很快就失去了它的光泽。感谢您能提供的任何信息。
INotifyPropertyChanged
ViewModel应实现INotifyPropertyChanged接口,并在属性更改时引发它。
public class MyViewModel : INotifyPropertyChanged
{
private string _firstName;
public event PropertyChangedEventHandler PropertyChanged;
public string FirstName
{
get { return _firstName; }
set
{
if (_firstName == value)
return;
_firstName = value;
PropertyChanged(this, new PropertyChangedEventArgs("FirstName"));
}
}
}
}
SetProperty<T>
。你可以将set方法减少到只有一行,ref参数允许你更新其值。下面的BindableBase代码来自INotifyPropertyChanged, The .NET 4.5 Way - Revisited。 public class MyViewModel : BindableBase
{
private string _firstName;
private string _lastName;
public string FirstName
{
get { return _firstName; }
set { SetProperty(ref _firstName, value); }
}
}
//Inside Bindable Base
public abstract class BindableBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
storage = value;
this.OnPropertyChanged(propertyName);
return true;
}
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
这不是两者之间的选择。
BindableBase实现了INotifyPropertyChanged接口。
因此,如果您使用BindableBase,则将使用INotifyPropertyChanged。
在使用数据绑定实现MVVM时,几乎必须使用INotifyPropertyChanged。
使用BindableBase还是其他实现取决于个人喜好和对Prism的使用情况。
在Rohit的回答基础上,如果你使用的是.NET 4.6,你可以利用Null-conditional运算符简化OnPropertyChanged方法的实现:
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
INotifyPropertyChanged, The .NET 4.6 Way 更详细地解释了它。
BindableBase
。它仍然非常光滑 :) - dub stylee