WPF ContextMenu itemtemplate, menuitem inside menuitem

前端 未结 1 770
[愿得一人]
[愿得一人] 2020-12-10 06:49

I have the following xaml:


     
          

        
相关标签:
1条回答
  • 2020-12-10 06:59

    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>
    

    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>
    

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

    0 讨论(0)
提交回复
热议问题