检测用户控件中的 DataContext 更改

And*_*ehi 4 c# xaml windows-phone-7 windows-phone-8

我正在实现一个UserControl,我想检测是否从代码中更改了 DataContext。FrameworkElement.DataContext.Get不是虚拟的,所以我不能覆盖它。我可以隐藏它,new但我相信有更好的方法来做到这一点。在 WPF 中有类似 DataContextChanged 事件的东西。我们可以用 Windows Phone 做类似的事情吗?

Ran*_*ngy 5

在您的用户控件构造函数中添加:

this.SetBinding(BoundDataContextProperty, new Binding());
Run Code Online (Sandbox Code Playgroud)

然后添加这些:

public static readonly DependencyProperty BoundDataContextProperty = DependencyProperty.Register(
    "BoundDataContext",
    typeof(object),
    typeof(MyUserControl),
    new PropertyMetadata(null, OnBoundDataContextChanged));

private static void OnBoundDataContextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    // e.NewValue is your new DataContext
    // d is your UserControl
}
Run Code Online (Sandbox Code Playgroud)