views:

944

answers:

4

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  A: 

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.

asterite
+1  A: 

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

Daniel Crenna
A: 

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

+2  A: 

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

amazedsaint
You're the man! I was struggling with this for hours before I found your answer.
Steve Wortham
Does this cause any problems with garbage collection? Will the lifetime of `element` be extended?
kpozin