【发布时间】:2010-09-19 09:40:03
【问题描述】:
在 Silverlight 应用程序中,我试图找出用户控件上的属性何时发生更改。我对一个特定的 DependencyProperty 感兴趣,但不幸的是,控件本身并没有实现 INotifyPropertyChanged。
是否有其他方法可以确定值是否已更改?
【问题讨论】:
标签: .net silverlight silverlight-2.0 dependency-properties
在 Silverlight 应用程序中,我试图找出用户控件上的属性何时发生更改。我对一个特定的 DependencyProperty 感兴趣,但不幸的是,控件本身并没有实现 INotifyPropertyChanged。
是否有其他方法可以确定值是否已更改?
【问题讨论】:
标签: .net silverlight silverlight-2.0 dependency-properties
你可以。至少我做到了。还是得看利弊。
/// 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-listening-to-dependency.html上查看我的帖子
【讨论】:
element 的生命周期会延长吗?
在 WPF 中你有 DependencyPropertyDescriptor.AddValueChanged,但不幸的是在 Silverlight 中没有这样的东西。所以答案是否定的。
也许如果你解释你想要做什么,你可以解决这种情况,或者使用绑定。
【讨论】:
正如 Jon Galloway 在另一个线程上发布的那样,您也许可以使用 WeakReference 之类的东西来包装您感兴趣的属性,然后在您自己的类中重新注册它们。这是 WPF 代码,但概念不依赖于 DependencyPropertyDescriptor。
【讨论】:
查看以下链接。它展示了如何在没有 DependencyPropertyDescriptor.AddValueChanged 的 silverlight 中解决问题
http://themechanicalbride.blogspot.com/2008/10/building-observable-model-in.html
【讨论】: