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"/>