我按照许多线程的建议实现了INotifyPropertyChanged
。
实施1
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string pName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(pName));
}
}
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("name_changed"); }
}
}
viewmodel由模型和命令组成,用于更改模型属性。
public class ViewModel : Notifier
{
private Model _model;
public Model Model
{
get { return _model; }
set { _model = value; OnPropertyChanged("model_changed"); }
}
private ICommand _cmd;
public ICommand Command
{
get { return _cmd; }
set { _cmd = value; }
}
public void ExecuteCommand(object para)
{
Console.WriteLine("Command executed");
Model.Name = "new name";
}
}
然后将VM绑定到视图。
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" Width="100">
<TextBox.Text>
<Binding Path="Model.Name" Mode="TwoWay" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True">
<Binding.ValidationRules>
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
执行命令时,TextBox
不会更新为新值。
但是,如果我像INotifyPropertyChanged
指令一样实现this,则绑定有效。
实施2
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected bool SetProperty<T>(ref T field, T newValue, [CallerMemberName]string propertyName = null)
{
if (!EqualityComparer<T>.Default.Equals(field, newValue))
{
field = newValue;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
return true;
}
return false;
}
}
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { SetProperty(ref name, value); }
}
}
第一种方法错过了什么?
请添加像这样的属性名称。
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged("Name"); }
}
}
实现1的主要问题是OnPropertyChanged
方法的字符串参数需要是正在更改的确切属性名称。对于你的两个例子,"model_changed"
应该改为"Model"
,而"name_changed"
应该读成"Name"
。以下两种很棒的技术可以通过输入文字字符串名来减轻潜在的人为错误:
1.使用CallerMemberName
属性
如果允许并且可以访问System.Runtime.CompilerServices
命名空间,则可以编写基类,以使属性名称自动作为OnPropertyChanged
方法的字符串参数传递:
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class Notifier : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName] string pName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(pName));
}
}
然后你可以简单地在你房产的吸气器里打电话给OnPropertyChanged()
。
2.使用nameof
关键字
或者,您可以简单地用nameof(<InsertPropertyNameHere>)
替换文字类型的属性名称,这将返回名称而不会有任何错误输入的风险,例如:
public class Model : Notifier, IDataErrorInfo
{
private string name;
public string Name
{
get { return name; }
set { name = value; OnPropertyChanged(nameof(Name)); }
}
}