Silverlight: How to receive notification of a change in an inherited DependencyProperty

MojoFilter picture MojoFilter · May 7, 2009 · Viewed 11.9k times · Source

I have a control which inherits from (you guessed it) Control. I want to receive a notification whenever the FontSize or Style properties are changed. In WPF, I would do that by calling DependencyProperty.OverrideMetadata(). Of course, useful things like that have no place in Silverlight. So, how might one receive those kinds of notifications?

Answer

amazedsaint picture amazedsaint · Dec 2, 2009

I think here is a better way. 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

Using Silverlight 4.0 beta.