问题描述
在实现INotifyPropertyChanged
时,我从不知道propertyName
的含义.因此,通常将INotifyPropertyChanged
实现为:
public class Data : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName = "") {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
private string itsID;
public string ID {
get { return itsID; }
set {
if (itsID != value) {
itsID = value;
NotifyPropertyChanged("ID");
}
}
}
我从不知道NotifyPropertyChanged(string propertyName)
的propertyName
参数.
- 那可以是任意字符串(如上例中的"MyID")吗?
- 或者.NET是否使用Reflection将其与类中的属性对齐,因此它必须与属性名称完全匹配?
- 如果
propertyName
与Property
的名称不完全一样,.NET是否会将整个对象视为changed
?
它本身不是.NET Framework本身,几乎是每个PropertyChanged
订阅者的一部分(其中的某些确实确实是作为框架),假设您通过发送属性名称按预期使用了接口.如果您发送属性MyID
更改的通知,则当另一个组件正在查看属性ID
时,它通常会看到该通知,比较名称,并得出此通知不适合我"的结论. /p>
I was never sure about the meaning of propertyName
when implementing INotifyPropertyChanged
. So generally you implement INotifyPropertyChanged
as:
public class Data : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName = "") {
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
private string itsID;
public string ID {
get { return itsID; }
set {
if (itsID != value) {
itsID = value;
NotifyPropertyChanged("ID");
}
}
}
I was never sure about the propertyName
argument to NotifyPropertyChanged(string propertyName)
.
- Can that be any arbitrary string (like "MyID" in the above example)?
- Or does .NET use Reflection to align it with a property in a class so it has to match the name of the property exactly?
- What if the
propertyName
doesn't match the name of theProperty
exactly, does .NET consider the entire object aschanged
?
It's not .NET Framework itself per se, it's pretty much every PropertyChanged
subscriber out there (some of which do indeed happen to be distributed as part of the framework) that assumes you use the interface as intended, by sending the property name. If you send a notification that the property MyID
has changed, when another component is looking at the property ID
, it will typically see the notification, compare the names, and conclude "this notification isn't for me".
这篇关于INotifyPropertyChanged和propertyName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!