【问题标题】:Is there a notification mechanism for when a dependency property has changed?当依赖属性发生变化时,是否有通知机制?
【发布时间】:2010-09-19 09:40:03
【问题描述】:

在 Silverlight 应用程序中,我试图找出用户控件上的属性何时发生更改。我对一个特定的 DependencyProperty 感兴趣,但不幸的是,控件本身并没有实现 INotifyPropertyChanged。

是否有其他方法可以确定值是否已更改?

【问题讨论】:

    标签: .net silverlight silverlight-2.0 dependency-properties


    【解决方案1】:

    你可以。至少我做到了。还是得看利弊。

     /// 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 的生命周期会延长吗?
    【解决方案2】:

    在 WPF 中你有 DependencyPropertyDescriptor.AddValueChanged,但不幸的是在 Silverlight 中没有这样的东西。所以答案是否定的。

    也许如果你解释你想要做什么,你可以解决这种情况,或者使用绑定。

    【讨论】:

      【解决方案3】:

      正如 Jon Galloway 在另一个线程上发布的那样,您也许可以使用 Wea​​kReference 之类的东西来包装您感兴趣的属性,然后在您自己的类中重新注册它们。这是 WPF 代码,但概念不依赖于 DependencyPropertyDescriptor。

      Article link

      【讨论】:

        【解决方案4】:

        查看以下链接。它展示了如何在没有 DependencyPropertyDescriptor.AddValueChanged 的​​ silverlight 中解决问题

        http://themechanicalbride.blogspot.com/2008/10/building-observable-model-in.html

        【讨论】: