我有一个ItemsControl
。该ItemsControl
具有上下文菜单。我的要求是在菜单项的单击上获取DataTemplate
的内容。我想删除数据模板项。我的示例代码如下:
<ItemsControl>
<ItemsControl.Resources>
<ContextMenu x:Key="listItem">
<MenuItem
Command="{Binding DataContext.ListRemoveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=2}}"
CommandParameter="{Binding PlacementTarget, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"
Header="Delete Panel" />
</ContextMenu>
</ItemsControl.Resources>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Background="White">
<Label Content="{Binding MyLabelContent}" />
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemControl>
我当前的CommandParameter
通过了ContentPresenter
。通过使用内容演示者,我得到了DataTemplate
。我也尝试过DataTemplate.FindName()
,但这也不起作用。请给我一个建议。
答案 0 :(得分:0)
您无需操纵DataTemplate
,但可以操纵DataContext
(又名VM)中的数据。
由于您使用的是ItemsControl
,因此您将没有SelectedItem
属性来知道选择了哪个属性。因此,您需要将ContextMenu
绑定到DataTemplate
内。
<DataTemplate>
<StackPanel Background="White">
<Label Content="{Binding MyLabelContent}">
<Label.ContextMenu>
<ContextMenu>
<MenuItem Command="{Binding DataContext.ListRemoveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl, AncestorLevel=3}}"
CommandParameter="{Binding MyLabelContent}"
Header="Delete Panel" />
</ContextMenu>
</Label.ContextMenu>
</Label>
</StackPanel>
</DataTemplate>
注意:
Command
的{{1}} RelativeSource
成长1 AncestorLevel
绑定到LabelContent 然后,您需要删除CommandParameter
内容。