All for .net, .net for all!

DataContextChanged event for WinRT

VBandi's blog



Generic Content

Unlike WPF, WinRT (or Windows Store App API) does not have a DataContextChanged event handler. This may cause problems if you are doing framework-y stuff, or even for some controls, where you are .

Luckily, Jeremy Likness wrote a solution for the exact same problem for Silverlight, back in 2009. Silverlight now has the DataContextChanged event implemented, but his technique is still useful for WinRT. There is a small change to do though: the way you perform callback from an attached property is a tiny bit different.

So, here is the complete code that compiles and works perfectly on WinRT. Again, all credit goes to Jeremy for this solution!

public static class DataContextChangedHelper<T> where T : FrameworkElement, IDataContextChangedHandler<T>
    private const string INTERNAL_CONTEXT = "InternalDataContext";

    public static readonly DependencyProperty InternalDataContextProperty =
                                    new PropertyMetadata(null, _DataContextChanged));

    private static void _DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        T control = (T)sender;
        control.DataContextChanged(control, e);

    public static void Bind(T control)
        control.SetBinding(InternalDataContextProperty, new Binding());

public interface IDataContextChangedHandler<T> where T : FrameworkElement
    void DataContextChanged(T sender, DependencyPropertyChangedEventArgs e);


To actually have the DataContextChanged event fire for your control (FrameworkElement), you have to add one more line in your control’s constructor:


That’s it!

Posted Jan 23 2013, 11:22 AM by vbandi


Dew Drop – January 23, 2013 (#1,485) | Alvin Ashcraft's Morning Dew wrote Dew Drop &ndash; January 23, 2013 (#1,485) | Alvin Ashcraft&#039;s Morning Dew
on Wed, Jan 23 2013 14:19

Pingback from  Dew Drop – January 23, 2013 (#1,485) | Alvin Ashcraft's Morning Dew

DataContextChanged event for WinRT wrote DataContextChanged event for WinRT
on Thu, Jan 24 2013 14:45

Pingback from  DataContextChanged event for WinRT