c# - WPF MVVM 绑定到父视图的 ViewModel 属性
问题描述
我有两种看法:
- ShellView - 数据上下文:ShellViewModel
- VolumeViewerView - 数据上下文:VolumeViewerViewModel
ShellView 是我程序的根目录,它包含 3 个 VolumeViewerView 对象(使用它们的 ViewModel 实例)。
在每种情况下,事情都运行得非常顺利且符合预期。
但是,在 VolumeViewerView 中,我有一个<Image>
我想从 ShellViewModel 控制的光标。
这是代码:
ShellView.xaml -MainView
是VolumeViewerViewModel
<Frame Grid.Row="1" Grid.Column="0" Grid.RowSpan="3" Content="{Binding MainView}"/>
ShellViewModel.cs
private Cursor _editorCursor;
public Cursor EditorCursor
{
get { return _editorCursor; }
set
{
_editorCursor = value;
NotifyOfPropertyChange(() => EditorCursor);
}
}
VolumeViewerView.xaml
<Image [OTHER PROPERTIES]
Cursor="{Binding Path=DataContext.EditorCursor,
RelativeSource={RelativeSource Mode=FindAncestor,
AncestorType={x:Type local:ShellView}}}"/>
当我将光标绑定到 VolumeViewerViewModel 中的一个属性时,一切都按预期工作。但在这里它没有连接。
我想知道,考虑到它们在不同的文件中,这是否可能?FindAncestor
仅在同一xaml
文件的上下文中有效吗?
如果不可能,有什么好的选择?我可以在每次设置in时创建EditorCursor
内部并设置它,但这看起来有点难看。如果这是唯一的方法,我可能会选择去那里。但我真的很喜欢建议!VolumeViewerViewModel
EditorCursor
ShellViewModel
解决方案
正如@Clemens 在评论中指出的那样,Visual Tree 以一个Frame
元素结束。这是我问题的根源。我已将子视图放在 aFrame
中,这意味着FindAncestor
无法找到父元素及其DataContext
.
我编辑了 ShellView.xaml,替换为Frame
:
<ContentControl Grid.Row="1" Grid.Column="0" Grid.RowSpan="3" Content="{Binding MainView}"/>
这意味着我还必须编辑子视图(它最初是继承Page
的,不能是 a 的内容ContentControl
)。我做到了UserControl
,绑定按预期工作。
推荐阅读
- asp.net-mvc - AADSTS750054:SAMLRequest 或 SAMLResponse 必须作为查询字符串参数出现在 SAML 重定向绑定的 HTTP 请求中
- r - 出了点问题;缺少所有准确度指标值:模型验证
- linux - Busybox 不运行控制台
- json - JSON数组上的“从不”类型不存在属性
- javascript - Jest 框架的 Vscode Launch 配置
- laravel - 如何在一个单元格中向 user_role 添加多个角色(LARAVEL 8x)
- node.js - 错误:检测到循环依赖(属性键:“firstName”)由 tx-mixer 抛出
- angular - 如何使用注入数据测试组件?
- python - Python 之间的语法(IF 语句)
- sql - 将信息从行排序到列