我刚刚开始一个将使用MVVM模式的Wpf项目。我已经建立了第一个模型,但与普通的网络模型相比,例如:
public string name {get;set;}
这些模型要复杂一些,因为它们正在实现INotifyPropertyChanged。
我创建了一个客户模型:
public class Customer : INotifyPropertyChanged
{
// Initizalize default construcktor
public Customer(string CustomerName)
{
Name = CustomerName;
}
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
OnPropertyChanged("Name");
}
}
}
然后我有些困惑,如果我选择Visual Studio 2015为我生成一个方法,则会得到类似以下内容的信息:
private void OnPropertyChanged(string v)
{
throw new NotImplementedException();
}
方法应该是什么?Visual Studio不能通过代码段为您做到这一点吗?像“ ctor”构造函数片段一样?
希望有人可以给我一些技巧,使过程更容易理解。
您需要实现INotifyPropertyChanged
接口。请注意,以下实现使您可以调用OnPropertyChanged()
(由于CallerMemberName
在方法签名中使用了属性)而不必传递属性名,这有助于减少错误并简化重构。
public class Customer : INotifyPropertyChanged
{
// Initizalize default construcktor
public Customer(string CustomerName)
{
Name = CustomerName;
}
private string _Name;
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected internal void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
请注意,创建抽象基类以实现INotifyPropertyChanged
模型将继承也是一种常见的做法。这样,您不必为每个模型都实现此功能,并且不需要大量的冗余代码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句