【发布时间】:2017-06-16 00:14:00
【问题描述】:
我正在尝试清理我在 UserControls 中使用 DataContexts 的方式,目前遇到了一个问题,我需要将 TabItem 内的 UserControl 数据绑定到父窗口的 DataContext。
这是我的窗口的草图:
如您所见,此窗口拥有一个 TabControl,其中包含通过“Tabs”ItemSource 动态添加的 TabItems。此时数据绑定正在工作,因为“选项卡”填充了选项卡 1。
选项卡 1 包含一个需要访问 DiagnosticsViewModel 中的多个字符串属性的 UserControl,但是当我运行我的应用程序时,输出窗口指示所有绑定都失败了。例如:
System.Windows.Data 错误:4:找不到绑定源 参考'RelativeSource FindAncestor, AncestorType='System.Windows.Window',AncestorLevel='1''。 绑定表达式:路径=属性 1;数据项=空;目标元素是 'Tab1UserControl'(名称='');目标属性是“UCName”(类型 '字符串')
选项卡 1 中 UserControl 的 XAML 如下所示:
<Grid>
<uc:Tab1UserControl UCName="{Binding Property1, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />
</Grid>
其中 UCName 是一个字符串 DependencyProperty。
如果我告诉 WPF 我要查找树并绑定到最近窗口的 DataContext,并且我的 Window 的 DataContext 设置为 DiagnosticsViewModel,为什么它不将它用于我的 UserControl 的 DataContext?我没有在我的 UserControl 中设置 DataContext = this,因为我过去多次做错了,期望我的 UserControl 能够从其父级继承 DataContext。
我想看看 Snoop 是否可以解决我的问题,但是这个 GUI 是从 MFC 应用程序中显示的,而且 Snoop 似乎无法附加到我的 WPF 对话框。
【问题讨论】:
标签: c# wpf xaml data-binding itemssource