本文底部的代码是我在控制台应用程序中使用的简化版本,用于实现INotifyPropertyChanged模式并跟踪类的哪些属性已更改,意味着已分配新值。
您可以将代码复制并粘贴到visual studio中,看看它工作正常。
但是,我真的不喜欢将字符串传递给方法HasPropertyChanged。你可以传递" whateverString"作为属性名称,应用程序编译。 我正在寻找一种技术,迫使调用者在编译时只传递一个类属性 。我能这样做吗?
请注意:
class Program
{
static void Main(string[] args)
{
DemoCustomer dc = new DemoCustomer();
dc.CustomerName = "Test Customer";
Console.WriteLine(dc.IsPropertyChanged("CustomerName"));
Console.WriteLine(dc.IsPropertyChanged("PhoneNumber"));
Console.ReadKey();
}
public class DemoCustomer : INotifyPropertyChanged
{
private Guid idValue = Guid.NewGuid();
private string customerNameValue = String.Empty;
private string phoneNumberValue = String.Empty;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public DemoCustomer()
{
PropertyChanged += DemoCustomer_PropertyChanged;
}
private Dictionary<String, bool> changedProperties = new Dictionary<string, bool>();
private void DemoCustomer_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
changedProperties[e.PropertyName] = true;
}
public bool IsPropertyChanged(string propertyName)
{
return changedProperties.ContainsKey(propertyName);
}
public Guid ID
{
get
{
return this.idValue;
}
}
public string CustomerName
{
get
{
return this.customerNameValue;
}
set
{
if (value != this.customerNameValue)
{
this.customerNameValue = value;
NotifyPropertyChanged();
}
}
}
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged();
}
}
}
}
}