Is there a notification mechanism for when a dependency property has changed?

。_饼干妹妹 提交于 2019-12-01 09:15:18

问题


In a Silverlight application I'm trying to find out when a property on a usercontrol has changed. I'm interested in one particular DependencyProperty, but unfortunately the control itself doesn't implement INotifyPropertyChanged.

Is there any other way of determining if the value has changed?


回答1:


In WPF you have DependencyPropertyDescriptor.AddValueChanged, but unfortunately in Silverlight there's no such thing. So the answer is no.

Maybe if you explain what are you trying to do you can workaround the situation, or use bindings.




回答2:


You can. Atleast I did. Still need to see the pros and Cons.

 /// 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);
    }

And now, you can call RegisterForNotification to register for a change notification of a property of an element, like .

RegisterForNotification("Text", this.txtMain,(d,e)=>MessageBox.Show("Text changed"));
            RegisterForNotification("Value", this.sliderMain, (d, e) => MessageBox.Show("Value changed"));

See my post here on the same http://amazedsaint.blogspot.com/2009/12/silverlight-listening-to-dependency.html




回答3:


As Jon Galloway posted on another thread, you might be able to use something like WeakReference to wrap properties you're interested in and re-register them in your own class. This is WPF code but the concept doesn't rely on DependencyPropertyDescriptor.

Article link




回答4:


Check out the following link. It showns how to get around the problem in silverlight where you don't have DependencyPropertyDescriptor.AddValueChanged

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



来源:https://stackoverflow.com/questions/240156/is-there-a-notification-mechanism-for-when-a-dependency-property-has-changed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!