【发布时间】:2010-08-12 17:04:48
【问题描述】:
通常在对象的属性设置器中,我们可能希望引发 PropertyChanged 事件,例如,
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
public string UserNote
{
get { return _userNote; }
set
{
_userNote = value;
Notify("UserNote");
}
}
在我们现有的代码库中,我看到将 PropertyChangedEventArgs 发送为 null 以指示对象的所有属性都已更改的实例。这似乎效率低下,并且似乎导致触发的事件比需要的多得多。它似乎也会导致对象以循环方式相互更新的问题。
这是一个好的做法吗?
代码中的注释试图证明它的合理性......
//The purpose of this method is to wire up clients of NotificationBase that are also
//NotificationBases to *their* clients. Consider the following classes:
public class ClassA : NotificationBase
{
public int Foo
{
get { return 123; }
set { Notify("Foo"); }
}
}
public class ClassB : NotificationBase
{
ClassA A = new ClassA();
public ClassB()
{
A.PropertyChanged += AllChanged;
}
public void SetFoo()
{
A.Foo = 456;
}
}
public class ClassC
{
ClassB B = new ClassB();
public ClassC()
{
B.PropertyChanged += delegate { dosomething(); };
B.SetFoo(); // causes "dosomething" above to be called
}
}
/// ClassB.SetFoo calls ClassA.Foo's setter, which calls ClassA.Notify("Foo").
/// The event registration in ClassB's ctor causes ClassB.AllChanged to be called, which calls
/// ClassB.Notify(null) - implying that ALL of ClassB's properties have changed.
/// The event registration in ClassC's ctor causes the "dosomething" delegate to be called.
/// So a Notify in ClassA is routed to ClassC via ClassB's PropertyChanged event.
protected void AllChanged(Object sender, PropertyChangedEventArgs e)
{
Notify(null);
}
任何想法都非常感谢。
问候, 呸呸呸
【问题讨论】:
-
您想要关于常规属性或 DependencyProperty 的信息吗?
-
如果不深入,该代码看起来有点吓人,试图描述该方法意图的大注释让我觉得很“臭”。你真正想做的是什么? Notification 事件的使用者应该决定在收到属性更改通知时他们需要做什么。
-
一个例子是我们有一个 Fixture 对象,它有一个 FixtureStatus 属性。还有许多其他属性依赖 FixtureStatus 来确定它们的值。我认为 Notify 方法应该使用每个依赖属性的名称而不是全部通知来调用。代码开始变得有点复杂,但每个依赖属性的 Notify 调用。
标签: wpf events propertychanged