Friday, January 23, 2009

Quickie: Simulating DataContextChanged in Silverlight

One of the key line-of-business-app features of Silverlight is the ability to databind – and we use it everywhere.

So it’s slightly odd that the DataContextChanged event is internal in Silverlight (it’s public in WPF). How on earth can we then know if our data context has been changed?

The answer’s pretty simple, and is properly documented on The Problem Solver blog.

The solution is to create a custom DependencyProperty and explicitly bind it, thus:

partial class PersonHeader : UserControl
        public PersonHeader()
            // Required to initialize variables
            SetBinding(DataContextWatcherProperty, new Binding());

        public static readonly DependencyProperty DataContextWatcherProperty =
                                        typeof (Object), typeof (PersonHeader),
                                        new PropertyMetadata(DataContextChanged));

        private static void DataContextChanged(object sender,
                                               DependencyPropertyChangedEventArgs e)
            var personHeader = (PersonHeader) sender;
            // Update the control as needed

DataContextChanged Solution:  

No comments: