Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将ICommand绑定到父视图模型_C#_.net_Wpf_Xaml - Fatal编程技术网

C# 将ICommand绑定到父视图模型

C# 将ICommand绑定到父视图模型,c#,.net,wpf,xaml,C#,.net,Wpf,Xaml,我有两个用户控件LeftPanel和DeviceList设备列表位于左侧面板内。我希望设备列表中的上下文菜单能够调用父视图模型上的命令,该模型设置在承载DeviceList的网格上。我尝试了以下方法,但不起作用 这是DeviceList <MenuItem Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:Lef

我有两个用户控件
LeftPanel
DeviceList
<代码>设备列表位于
左侧面板内
。我希望设备列表中的上下文菜单能够调用父视图模型上的命令,该模型设置在承载
DeviceList
的网格上。我尝试了以下方法,但不起作用

这是
DeviceList

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

我有一个类似的问题,但是ContextMenu没有看到ViewModel或父对象的DataContext。
这里有一个可能的解决方案。

上下文菜单不是visualtree的一部分,因此我认为您的绑定是错误的,因为datacontext不是您所想的

用于在运行时检查DataContext和绑定


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

我想说的是不要这样做。让您的
DeviceListView
调用
DevicelistViewModel
中的命令,并从该虚拟机向其父虚拟机发送“消息”,并相应地采取行动。不要在多个虚拟机之间绑定视图。很快就会变得很混乱
<UserControl x:Class="Tool.LeftPanel" .... >
    <Grid DataContext="{Binding DeviceListViewModel}" Grid.Column="1">
        <local:DeviceList Grid.Row="1" Margin="0,0,0,10"/>