WPF命令绑定ItemsControl内的ContextMenu项 [英] WPF Command Binding of ContextMenu Item inside ItemsControl
问题描述
我的应用程序由一个MainWindow
和一个ContentControl
组成,我根据所选菜单更改ViewModel.
My Application consists of a MainWindow
with a ContentControl
and I change the ViewModel depending on the selected menu.
我显示为内容的UserControl之一包含以下WrapPanel
:
One of the UserControls I display as content contains the following WrapPanel
:
<UserControl ...>
<Grid>
<WrapPanel>
<ItemsControl ItemsSource="{Binding Connections}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Command="{Binding DataContext.ConnectionSelectCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
FocusManager.FocusedElement="{Binding ElementName=InstanceName}"
Style="{DynamicResource DashboardButton}">
<TextBlock TextWrapping="Wrap" HorizontalAlignment="Center" Text="{Binding Name}" />
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete"
Command="{Binding ConnectionRemoveCommand}"
CommandParameter="{Binding}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</WrapPanel>
</Grid>
</UserControl>
ContextMenu
上的Command
无效,因为它尝试调用Connection
对象上的ConnectionRemoveCommand
而不是ConnectionViewModel
(即UserControl
的DataContext
).
The Command
on the ContextMenu
doesn't work because it tries to call ConnectionRemoveCommand
on the Connection
object instead of the ConnectionViewModel
which is the DataContext
of the UserControl
.
如何如何将Command
绑定到ConnectionViewModel
,并且CommandParameter
是Connection
对象?
How do I bind the Command
to the ConnectionViewModel
with the CommandParameter
being the Connection
object?
推荐答案
如果将Button
的Tag
属性绑定到ItemsControl
的DataContext
,则可以使用<ContextMenu
的c18>:
If you bind the Tag
property of the Button
to the DataContext
of the ItemsControl
, you could then bind to it using the PlacementTarget
of the ContextMenu
:
<Button Command="{Binding DataContext.ConnectionSelectCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
FocusManager.FocusedElement="{Binding ElementName=InstanceName}"
Style="{DynamicResource DashboardButton}"
Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ItemsControl}}">
<TextBlock TextWrapping="Wrap" HorizontalAlignment="Center" Text="{Binding Name}" />
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Delete"
Command="{Binding PlacementTarget.Tag.ConnectionRemoveCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" />
</ContextMenu>
</Button.ContextMenu>
</Button>
这篇关于WPF命令绑定ItemsControl内的ContextMenu项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!