Silverlight : Listening to Dependency Property Change notification of a given Element

By Anoop Madhusudanan

Vote on HN

I was digging a bit around Silverlight Dependency properties, mainly to see how to receive change notification when ever a dependency property is changed. In WPF, this is straight forward, you may use the DependencyPropertyDescriptor, and call AddValueChanged. Like this.

DependencyPropertyDescriptor desc = 
    (UIElement.VisibilityProperty, typeof(UIElement));

  (this.myLabel, new EventHandler(VisibilityChanged));


Now, how to do this in Silverlight? I roamed around a bit, but can't really find a good way of doing that. So, here is a quick hack. The trick is to use DependencyProperty.RegisterAttached(..) to instantiate a dependency property type (Ahem). This is what we are doing below.

  • Create a binding with the FrameworkElement as the source
  • Use DependencyProperty.RegisterAttached(..) to create a DependencyProperty instance
  • Use FrameworkElement.SetBinding(dp, binding) to associate the dependency property with the element, via the binding.

So, we’ll get a call back when ever the dependency property changes. The RegisterForNotification summarizes what I explained above.

        /// 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(
                new System.Windows.PropertyMetadata(callback));

            element.SetBinding(prop, b);


Create a new Silverlight project, and add the above code to the code behind. And add the following controls to your xaml page..

   <Grid x:Name="LayoutRoot" Background="White">
        <TextBox Text="hello" x:Name="txtMain" />
        <Slider Value="10" Minimum="0" Maximum="100" x:Name="sliderMain"/>


Now, just call RegisterForNotification from where ever you need (I’ve it in the Constructor of my MainPage.cs, just under the InitializeComponent() call), like

//Shows a message box when the text of Textbox or value of Slider changes.

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


Fire up your project, and you’ll see the message boxes when ever the value change happens. So, now it looks pretty interesting, I guess. Opens up possibilities like having Data triggers in Silverlight, probably via an attached behaviour. Need to evaluate the pros and cons of this approach, came across this scenario while doing some other hacks. What do you think?

Stay tuned, follow me on twitter.  Happy Coding!!

Shout it
© 2012. All Rights Reserved.