Error binding WPF menu to ItemsSource

I would like to avoid having to create a menu manually in XAML or code by associating it with a list of ICommand-derived objects . However, I had a small problem when the resulting menu has two levels of menu items (that is, each is MenuItemcontained in MenuItem):

alt text

I suppose this is because WPF automatically generates MenuItemfor my binding, but the "viewer" that I use is actually already MenuItem(it is derived from MenuItem):

<ContextMenu
    x:Name="selectionContextMenu"
    ItemsSource="{Binding Source={x:Static OrangeNote:Note.MultiCommands}}"
    ItemContainerStyleSelector="{StaticResource separatorStyleSelector}">
    <ContextMenu.ItemTemplate>
        <DataTemplate>
            <Viewers:NoteCommandMenuItemViewer
                CommandParameter="{Binding Source={x:Static OrangeNote:App.Screen}, Path=SelectedNotes}" />
        </DataTemplate>
    </ContextMenu.ItemTemplate>
</ContextMenu>

(ItemContainerStyleSelector from http://bea.stollnitz.com/blog/?p=23 , which allows me to have items Separatorinside my linked source.)

, ICommand, CommandParameter ( , ).

, , WPF MenuItem?

+3
2

ContextMenu GetContainerForItemOverride:

public class ContextMenuWithNoteCommands : ContextMenu
{
  protected virtual DependencyObject GetContainerForItemOverride()
  {
    return new NoteCommandMenuItemViewer();
  }
}

CommandParameter NoteCommandMenuItemViewer ContextMenu.ItemContainerStyle, , .

, ItemContainerStyle MenuItem, :

<ContextMenu ...>
  <ContextMenu.ItemContainerStyle>
    <Style>
      ...
    </Style>
  </ContextMenu.ItemContainerStyle>
</ContextMenu>
+2

, - MenuItems, ItemTemplate. . - , :

<Style x:Key="SelectionContextMenuStyle" TargetType="MenuItem">
    <Setter Property="Header" Value="{Binding Path=Text}" />
    <Setter Property="Command" Value="{Binding Path=Command}" />
    <Setter Property="CommandParameter" Value="{Binding Path=Parameter}" />
</Style>

, ItemTemplate , , , , .

+3

Source: https://habr.com/ru/post/1749638/


All Articles