Thursday Night

Paul Betts’s personal website / blog / what-have-you

Watching DependencyProperties using ReactiveUI

Watching DependencyProperties in WPF is easy…

One of the things that is pretty useful in XAML-based frameworks like WPF and Silverlight when working in the codebehind is being able to be notified when a DependencyProperty changes. In the ViewModel, we have a different mechanism called INotifyPropertyChanged to accomplish this, but DependencyProperties are still an important part of WPF/Silverlight.

Let’s see how we would do this in WPF – it’s fairly straightforward:

…but really ugly in Silverlight

Unfortunately, this isn’t possible in Silverlight – it’s only possible to wire up a single callback, and it can only be done by the class that actually creates the DependencyProperty. This might work fine in some scenarios, but something less tightly coupled is often needed.

The solution is to use Attached Properties, as described Anoop Madhusudanan’s blog post – register an attached property, then hook that change notification.

ReactiveUI now does this for you

In ReactiveUI as of v2.0, there is a new method called ObservableFromDP – this method works similarly to the ViewModel’s ObservableFromProperty, but with less syntactic noise:

Of course, since it’s an Observable and not an event handler, all of the power of Rx.NET applies to this as well. Nothing revolutionary, but definitely makes things easier!

Written by Paul Betts

February 4th, 2011 at 8:10 pm