WPF ContextMenu itemtemplate,menuitem中的menuitem [英] WPF ContextMenu itemtemplate, menuitem inside menuitem

查看:503
本文介绍了WPF ContextMenu itemtemplate,menuitem中的menuitem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下xaml:

<ContextMenu ItemsSource="{Binding TestItems}">
     <ContextMenu.ItemTemplate>
          <DataTemplate DataType="models:TestItemModel">
              <MenuItem IsChecked="{Binding IsSelected}" Header="{Binding Header}"  />
          </DataTemplate>
     </ContextMenu.ItemTemplate>
</ContextMenu>

TestItemModel类仅由IsSelected布尔属性和Header字符串属性组成.

The TestItemModel class only consists of a IsSelected boolean property and a Header string property.

TestItems是TestItemModels的列表.

TestItems is a list of TestItemModels.

数据绑定到上下文菜单,但在UI中作为MenuItem内的MenuItem反映出来(带有附加的空白,因此菜单非常大).我可以通过将DataTemplate内的MenuItem更改为TextBox来解决此问题,但是之后我将无法再绑定IsSelected(我需要可视化属性).

The data is binded to the contextmenu but it is reflected in the UI as a MenuItem inside a MenuItem (with the additional margins as such, making the menu very big). I can fix this by changing the MenuItem inside the DataTemplate to a TextBox, but then I cannot bind the IsSelected anymore (which I need for visualization properties).

我对此有两个疑问:

  • 为什么MenuItem中有一个MenuItem?这对我来说没有意义,因为它没有绑定到菜单项列表,而是绑定到TestItemModels列表.
  • 我该如何解决?

推荐答案

由于MenuItem是容器类型,当将视图模型转换为可视项时,会将模板包装在MenuItem中.以相同的方式ListBox将创建ListBoxItemListView将使用ListViewItem.要绑定包装器的属性,您需要使用ItemContainerStyle

Because MenuItem is the container type and when it translates your view model into visual item it will wrap your template in MenuItem. In the same way ListBox will create ListBoxItem or ListView will use ListViewItem. To bind properties of the wrapper you need to use ItemContainerStyle

<ContextMenu ItemsSource="{Binding TestItems}">
   <ContextMenu.ItemContainerStyle>
      <Style TargetType="{x:Type MenuItem}">
         <Setter Property="IsChecked" Value="{Binding IsSelected}"/>
         <Setter Property="Header" Value="{Binding Header}"/>
      </Style>
   </ContextMenu.ItemContainerStyle>
</ContextMenu>

,或者,如果愿意,可以使用ItemTemplateItemContainerStyle

or, if you prefer, you can do it partially with ItemTemplate and ItemContainerStyle

<ContextMenu ItemsSource="{Binding TestItems}">
   <ContextMenu.ItemTemplate>
      <DataTemplate>
         <TextBlock Text="{Binding Header}"/>
      </DataTemplate>
   </ContextMenu.ItemTemplate>
   <ContextMenu.ItemContainerStyle>
      <Style TargetType="{x:Type MenuItem}">
         <Setter Property="IsChecked" Value="{Binding IsSelected}"/>
      </Style>
   </ContextMenu.ItemContainerStyle>
</ContextMenu>

在这种情况下,ItemTemplate中的所有内容都将变为MenuItem.Header,但是IsChecked属性仍需要绑定在ItemContainerStyle

In this scenario whatever is in ItemTemplate will become MenuItem.Header but IsChecked property still needs to be bound in ItemContainerStyle

这篇关于WPF ContextMenu itemtemplate,menuitem中的menuitem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆