Listening to a Dependency Property’s Change notification
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.
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.
Create a new Silverlight project, and add the above code to the code behind. And add the following controls to your xaml page.
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
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.
Original blog post by Anoop Madhusudanan: http://www.amazedsaint.com/2009/12/silverlight-listening-to-dependency.html