在WinRT程序中获取DataContext变化事件

WinRT程序中Control没有DataContextChanged事件,导致在使用过程中带来不少不便,如何获取DataContext变化事件,本文给了一个简单的解决方案:

首先注册一个带回调函数的依赖属性:

    public static readonly DependencyProperty MyDataContextProperty =
        DependencyProperty.Register("MyDataContext",
                                    typeof(Object),
                                    typeof(MainPage),
                                    new PropertyMetadata(MyDataContextChanged));    

然后,将依赖属性和我们要监控的DataContext绑定起来,

    SetBinding(MyDataContextProperty, new Binding());

这样,当依赖属性MyDataCntextProperty变化时,便会执行回调函数MyDataContextChanged,通过回调函数的参数即可获取DataContext的变化。

    private static void MyDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("DataContext Changed. Old value:{0}, New value {1}", e.OldValue, e.NewValue);
    }

原文地址:https://www.cnblogs.com/TianFang/p/2803744.html