如何从ItemsControl获取DataTemplate的内容?

时间:2018-07-20 08:53:24

标签: .net wpf xaml

我有一个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(),但这也不起作用。请给我一个建议。

1 个答案:

答案 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内容。