检测用户控件中DataContext的更改

4

我正在实现一个 UserControl , 我想要检测代码中的 DataContext 是否改变。但是 FrameworkElement.DataContext.Get 不是虚方法,所以我不能重写它。我可以用 new 隐藏它,但我相信有更好的方法来解决这个问题。在 WPF 中有类似 DataContextChanged 事件的东西。我们能否在 Windows Phone 上做类似的事情?

4个回答

5
在您的用户控件构造函数中添加以下内容:
this.SetBinding(BoundDataContextProperty, new Binding());

然后添加这些内容:
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
}

1

UserControl类有内部事件UserControl_DataContextChanged,可用于订阅此目的

<UserControl 
         DataContextChanged="UserControl_DataContextChanged">

0

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接