Is there a notification mechanism for when a depen

2019-05-28 15:02发布

问题:

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