【问题标题】:Accessing a child user control's data context in the parent在父级中访问子用户控件的数据上下文
【发布时间】:2012-03-02 11:21:19
【问题描述】:

在我的 WPF+MVVM 应用程序中,我有一个承载另一个用户控件的视图。子用户控件不遵循 MVVM 方式(因为我只是在那里托管了一个 Visio activeX 对象),所以我使用的是类后面的代码。

在视图中我正在使用此代码:

<uc:VisioControl Grid.Row="2" x:Name="visioControlUC"
        VisioFileName="{Binding ElementName=tbFullFileName,Path=Text, UpdateSourceTrigger=PropertyChanged}"/>

在同一个视图中,我有一个 Label 元素,我想在其中显示在子用户控件上定义的名为 SelectedNodeCustomPropertiesDependencyProperty 的字段值

<Label x:Name="lbNodeIdValue" DataContext="{Binding ElementName=visioControlUC}" Content="{Binding Path=SelectedNodeCustomProperties.Id, UpdateSourceTrigger=PropertyChanged}"/>

但是,这不起作用。在调试模式下运行我可以在输出窗口中看到这个绑定异常:

 BindingExpression path error: 'visioControlUC' property not found on 'object' ''NSDVizualizerViewModel' (HashCode=65573909)'. BindingExpression:Path=visioControlUC.SelectedNodeCustomProperties.NodeId; DataItem='NSDVizualizerViewModel' (HashCode=65573909); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')

那么,为什么期望在视图模型中定义子用户控件,以及如何在绑定标签内容时将 DataContext 设置为用户控件?

谢谢,

阿德里安

编辑:对于否决我的问题的人,也许你可以解释为什么?论坛有没有类似的问题我没找到可能?

【问题讨论】:

    标签: wpf data-binding mvvm


    【解决方案1】:

    试试

    <Label x:Name="lbNodeIdValue" 
           Content="{Binding ElementName=visioControlUC, 
                             Path=SelectedNodeCustomProperties.Id,
                             UpdateSourceTrigger=PropertyChanged}"/>
    

    【讨论】:

    • 我做到了。它仍然抛出异常System.Windows.Data Error: 40 : BindingExpression path error: 'SelectedNodeCustomProperties' property not found on 'object' ''RelativeSource' (HashCode=51797270)'. BindingExpression:Path=SelectedNodeCustomProperties.NodeId; DataItem='RelativeSource' (HashCode=51797270); target element is 'Label' (Name=''); target property is 'Content' (type 'Object')
    • RelativeSource 在哪里?您在 Binding 中使用了 ElementName 还是 RelativeSource
    • 我用 ElementName &lt;Label x:Name="lbNodeIdValue" Content="{Binding ElementName=visioControlUC, Path=SelectedNodeCustomProperties.Id, UpdateSourceTrigger=PropertyChanged}"/&gt;
    • Pff 在后面代码的其他地方发现了错误。我在临时变量上设置值,而不是 visioControlUC 对象上的 DependencyProperty。感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2013-04-08
    • 2015-07-29
    • 2011-01-16
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    相关资源
    最近更新 更多