首页 > 解决方案 > WPF MVVM 绑定到父视图的 ViewModel 属性

问题描述

我有两种看法:

ShellView 是我程序的根目录,它包含 3 个 VolumeViewerView 对象(使用它们的 ViewModel 实例)。

在每种情况下,事情都运行得非常顺利且符合预期。

但是,在 VolumeViewerView 中,我有一个<Image>我想从 ShellViewModel 控制的光标。

这是代码:

ShellView.xaml -MainViewVolumeViewerViewModel

<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内部并设置它,但这看起来有点难看。如果这是唯一的方法,我可能会选择去那里。但我真的很喜欢建议!VolumeViewerViewModelEditorCursorShellViewModel

标签: c#wpfmvvm

解决方案


正如@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,绑定按预期工作。


推荐阅读