BindableBase与INotifyChanged

有谁知道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")); } } } } 

问题在于ICommand接口,因为大多数代码都是重复的,因为它通过字符串变得容易出错。

Bindablebase是一个实现INotifyPropertyChanged接口并提供SetProperty的抽象类。您可以将set方法减少到只有一行,ref参数允许您更新其值。 下面的BindableBase代码来自INotifyPropertyChanged,.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(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。

使用DataBinding实现MVVM时,或多或少强制使用INotifyPropertyChanged。

是否使用BindableBase或其他实现取决于Prism的偏好和使用。

要扩展Rohit的答案,如果您使用的是.NET 4.6,则可以利用Null条件运算符并以下列方式简化OnPropertyChanged方法:

 protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } 

INotifyPropertyChanged,.NET 4.6 Way更详细地解释了它。