是否存在依赖属性更改时的通知机制?
-
04-07-2019 - |
题
在Silverlight应用程序中,我试图找出usercontrol上的属性何时发生了变化。我对一个特定的DependencyProperty感兴趣,但不幸的是控件本身没有实现INotifyPropertyChanged。
有没有其他方法可以确定值是否已更改?
解决方案
在WPF中,你有 DependencyPropertyDescriptor.AddValueChanged ,但不幸的是在Silverlight中没有这样的东西。所以答案是否定的。
也许如果你解释你想要做什么,你可以解决这种情况,或者使用绑定。
其他提示
你可以。至少我做到了。仍然需要看到利弊。
/// Listen for change of the dependency property
public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{
//Bind to a depedency property
Binding b = new Binding(propertyName) { Source = element };
var prop = System.Windows.DependencyProperty.RegisterAttached(
"ListenAttached"+propertyName,
typeof(object),
typeof(UserControl),
new System.Windows.PropertyMetadata(callback));
element.SetBinding(prop, b);
}
现在,您可以调用RegisterForNotification来注册元素属性的更改通知,例如。
RegisterForNotification("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
RegisterForNotification("Value", this.sliderMain, (d, e) => MessageBox.Show("Value changed"));
请在同一 http:// amazedsaint上查看我的帖子.blogspot.com / 2009/12 / Silverlight的收听到dependency.html
正如Jon Galloway在另一个帖子上发布的那样,你可以使用像WeakReference这样的东西来包装你感兴趣的属性,并在你自己的类中重新注册它们。这是WPF代码,但该概念不依赖于DependencyPropertyDescriptor。
查看以下链接。它展示了如何解决Silverlight中没有DependencyPropertyDescriptor.AddValueChanged
的问题http://themechanicalbride.blogspot.com/2008 /10/building-observable-model-in.html
不隶属于 StackOverflow