将命令绑定到父视图模型

本文关键字:视图 模型 命令 绑定 | 更新日期: 2023-09-27 18:16:09

我有两个用户控件LeftPanelDeviceListDeviceListLeftPanel内部。我希望设备列表中的上下文菜单能够调用父视图模型上的命令,该命令设置在承载DeviceList的网格上。我尝试了以下方法,但它不起作用

这是DeviceList

中的ContextMenu
<MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                    AncestorType={x:Type local:LeftPanel}},
                    Path=DeviceListViewModel.RemoveDevice}">

LeftPanel usercontrol

<UserControl x:Class="Tool.LeftPanel" .... >
    <Grid DataContext="{Binding DeviceListViewModel}" Grid.Column="1">
        <local:DeviceList Grid.Row="1" Margin="0,0,0,10"/>

将命令绑定到父视图模型

我有一个类似的问题,但是ContextMenu没有看到ViewModel或Parent的DataContext。一个可能的解决方案是在这里访问ViewModel/DataConext内的ContextMenu

上下文菜单不是visualtree的一部分,所以我认为你的绑定是完全错误的,因为数据上下文不是你想的那样。

使用Snoop在运行时检查你的DataContext和绑定

我假设你必须在你的绑定中使用PlacementTarget