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:


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

        public static readonly DependencyProperty DataContextWatcherProperty =
            DependencyProperty.Register("DataContextWatcher",
                                        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: http://msmvps.com/blogs/theproblemsolver/archive/2008/12/29/how-to-know-when-the-datacontext-changed-in-your-control.aspx  

No comments: