【发布时间】:2014-10-01 18:10:39
【问题描述】:
我找到了一个属性更改事件的实现,我可以在其中调用属性更改而无需网络中的属性名称。然后我用它构建了一个扩展方法,就在这里
public static void OnPropertyChanged(this INotifyPropertyChanged iNotifyPropertyChanged, string propertyName = null)
{
if (propertyName == null)
propertyName = new StackTrace().GetFrame(1).GetMethod().Name.Replace("set_", "");
FieldInfo field = iNotifyPropertyChanged.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic);
if (field == (FieldInfo) null)
return;
object obj = field.GetValue((object) iNotifyPropertyChanged);
if (obj == null)
return;
obj.GetType().GetMethod("Invoke").Invoke(obj, new object[2]
{
(object) iNotifyPropertyChanged,
(object) new PropertyChangedEventArgs(propertyName)
});
}
所以我可以这样调用属性更改:
private bool _foo;
public bool Foo
{
get { _foo; }
private set
{
_foo = value;
this.OnPropertyChanged();
}
}
但我想,如果我在使用 Property changed 时不必实现 Property 的 getter 和 setter 会更好。
现在有人如何将 OnPropertyChanged 方法实现为属性,也许使用 AOP?
这样 Auto-Property 可以用于 Property Changed 像这样:
[OnPropertyChanged]
public bool Foo {set;get;}
【问题讨论】:
-
另一件事,而不是做昂贵的 StackFrame 展开使用这个:stackoverflow.com/questions/22580623/…
标签: c# wpf inotifypropertychanged