gpt4 book ai didi

c# - BindableBase 与 INotifyChanged

转载 作者:可可西里 更新时间:2023-11-01 08:01:41 26 4
gpt4 key购买 nike

有谁知道 BindableBase 是否仍然可行,或者我们应该坚持使用 INotifyChanged 事件?看起来 BindableBase 很快就失去了光彩。感谢您提供的任何信息。

最佳答案

INotifyPropertyChanged

ViewModel 应该实现 INotifyPropertyChanged 接口(interface)并且应该在属性改变时引发它

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 接口(interface)上,因为大部分代码都是重复的,而且由于它传递字符串,因此很容易出错。

Bindablebase 是一个抽象类,它实现了INotifyPropertyChanged 接口(interface)并提供了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));
}
}
}

关于c# - BindableBase 与 INotifyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28844518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com