Chi*_*ago 13 c# wpf prism inotifypropertychanged
有谁知道BindableBase是否仍然可行还是我们应该坚持使用INotifyChanged事件?好像BindableBase很快就失去了光彩.感谢您提供的任何信息.
Roh*_*hit 27
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"));
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于ICommand接口,因为大多数代码都是重复的,因为它传递字符串变得容易出错.
而Bindablebase是一个实现INotifyPropertyChanged接口并提供的抽象类SetProperty<T>.您可以将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<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));
}
}
}
Run Code Online (Sandbox Code Playgroud)
它不是这两者之间的选择.
BindableBase实现了INotifyPropertyChanged.
因此,如果您使用BindableBase,您将使用INotifyPropertyChanged.
使用DataBinding实现MVVM时,或多或少强制使用INotifyPropertyChanged.
是否使用BindableBase或其他实现取决于Prism的偏好和使用.
| 归档时间: |
|
| 查看次数: |
20201 次 |
| 最近记录: |