【问题标题】:Setting DataContext makes PropertyChanged null in UserControl设置 DataContext 使 UserControl 中的 PropertyChanged 为空
【发布时间】:2011-10-20 04:42:03
【问题描述】:

我有一个使用 WPF 用户控件的 WPF 应用程序。

用户控件公开了一个我想在我的 WPF 应用程序中绑定到的 DependencyProperty。

只要我的用户控件没有设置自己的 DataContext 就可以了,并且我可以监听 DependencyProperty 中的变化。

但是,当我设置 DataContext 时,调用的 PropertyChanged 为空。

我在这里错过了什么?

代码示例: https://skydrive.live.com/redir.aspx?cid=367c25322257cfda&page=play&resid=367C25322257CFDA!184

【问题讨论】:

  • 如果您在此处发布一个演示问题的简单代码示例,而不是发布指向外部站点的链接,您将获得更多帮助...

标签: wpf dependency-properties datacontext inotifypropertychanged


【解决方案1】:

DependencyProperty具有继承属性,所以如果不设置UserControlDP的DataContext,则DataContext继承自MainWindow的DataContext。在这种情况下,下面代码中的 UserControlDP 的 DataContext 设置为MainWindow_ViewModel。因此,绑定被正确执行。

<usercontrol:UserControlDP Width="200" Height="100"
    TestValue="{Binding TestValueApp, Mode=TwoWay, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}"
    Margin="152,54,151,157"></usercontrol:UserControlDP>

在另一种情况下,UserControlDP 的 DataContext 设置为 UserControlDP_ViewModel,因此绑定被破坏。您可以在调试窗口中看到如下第一条异常消息。

System.Windows.Data Error: 40 : BindingExpression path error: 'TestValueApp' property not found on 'object' ''UserControlDP_ViewModel' (HashCode=24672987)'. BindingExpression:Path=TestValueApp; DataItem='UserControlDP_ViewModel' (HashCode=24672987); target element is 'UserControlDP' (Name=''); target property is 'TestValue' (type 'Object')

【讨论】:

    【解决方案2】:

    考虑在 UserControl 中包含的元素之一上设置 DataContext,而不是在 UserControl 本身上。

    【讨论】:

      【解决方案3】:

      感谢您的意见和澄清细节。

      经过深思熟虑后,我采取了简单的方法并从控件中删除了 ViewModel。 MVVM 用于应用程序,但没有用于用户控件的 MVVM。

      这样我不在用户控件中使用任何绑定,而是使用在主应用程序中绑定的依赖属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-12
        • 2011-01-06
        • 2021-07-20
        • 2011-07-01
        • 2015-02-16
        • 2012-11-24
        • 1970-01-01
        • 2021-07-19
        相关资源
        最近更新 更多