How can I bind an ObservableCollection of ViewModels to a MenuItem? How can I bind an ObservableCollection of ViewModels to a MenuItem? wpf wpf

How can I bind an ObservableCollection of ViewModels to a MenuItem?


I found using MVVM with MenuItems to be very challenging. The rest of my application uses DataTemplates to pair the View with the ViewModel, but that just doesn't seem to work with Menus because of exactly the reasons you've described. Here's how I eventually solved it. My View looks like this:

<DockPanel><Menu DockPanel.Dock="Top" ItemsSource="{Binding Path=(local:MainViewModel.MainMenu)}">    <Menu.ItemContainerStyle>        <Style>            <Setter Property="MenuItem.Header" Value="{Binding Path=(contracts:IMenuItem.Header)}"/>            <Setter Property="MenuItem.ItemsSource" Value="{Binding Path=(contracts:IMenuItem.Items)}"/>            <Setter Property="MenuItem.Icon" Value="{Binding Path=(contracts:IMenuItem.Icon)}"/>            <Setter Property="MenuItem.IsCheckable" Value="{Binding Path=(contracts:IMenuItem.IsCheckable)}"/>            <Setter Property="MenuItem.IsChecked" Value="{Binding Path=(contracts:IMenuItem.IsChecked)}"/>            <Setter Property="MenuItem.Command" Value="{Binding}"/>            <Setter Property="MenuItem.Visibility" Value="{Binding Path=(contracts:IMenuItem.Visible),                 Converter={StaticResource BooleanToVisibilityConverter}}"/>            <Setter Property="MenuItem.ToolTip" Value="{Binding Path=(contracts:IMenuItem.ToolTip)}"/>            <Style.Triggers>                <DataTrigger Binding="{Binding Path=(contracts:IMenuItem.IsSeparator)}" Value="true">                    <Setter Property="MenuItem.Template">                        <Setter.Value>                            <ControlTemplate TargetType="{x:Type MenuItem}">                                <Separator Style="{DynamicResource {x:Static MenuItem.SeparatorStyleKey}}"/>                            </ControlTemplate>                        </Setter.Value>                    </Setter>                </DataTrigger>            </Style.Triggers>        </Style>    </Menu.ItemContainerStyle></Menu></DockPanel>

If you notice, I defined an interface called IMenuItem, which is the ViewModel for a MenuItem. Here's the code for that:

public interface IMenuItem : ICommand{    string Header { get; }    IEnumerable<IMenuItem> Items { get; }    object Icon { get; }    bool IsCheckable { get; }    bool IsChecked { get; set; }    bool Visible { get; }    bool IsSeparator { get; }    string ToolTip { get; }}

Notice that the IMenuItem defines IEnumerable Items, which is how you get sub-menus. Also, the IsSeparator is a way to define separators in the menu (another tough little trick). You can see in the xaml how it uses a DataTrigger to change the style to the existing separator style if IsSeparator is true. Here's how MainViewModel defines the MainMenu property (that the view binds to):

public IEnumerable<IMenuItem> MainMenu { get; set; }

This seems to work well. I assume you could use an ObservableCollection for the MainMenu. I'm actually using MEF to compose the menu out of parts, but after that the items themselves are static (even though the properties of each menu item are not). I also use an AbstractMenuItem class that implements IMenuItem and is a helper class to instantiate menu items in the various parts.

UPDATE:

Regarding your color problem, does this thread help?


Don't put the MenuItem in the DataTemplate. The DataTemplate defines the content of the MenuItem. Instead, specify extraneous properties for the MenuItem via the ItemContainerStyle:

<Menu>    <Menu.ItemContainerStyle>        <Style TargetType="MenuItem">            <Setter Property="Header" Value="{Binding Title}"/>            ...        </Style>    </Menu.ItemContainerStyle>    <MenuItem         Header="Options" ItemsSource="{Binding ManageMenuPageItemViewModels}"              ItemTemplate="{StaticResource MainMenuTemplate}"/></Menu>

Also, take a look at HierarchicalDataTemplates.


Here is how I have done my menus. It may not be precisely what you need, but I think it is pretty close.

  <Style x:Key="SubmenuItemStyle" TargetType="MenuItem">    <Setter Property="Header" Value="{Binding MenuName}"></Setter>    <Setter Property="Command" Value="{Binding Path=MenuCommand}"/>    <Setter Property="ItemsSource" Value="{Binding SubmenuItems}"></Setter>  </Style>  <DataTemplate DataType="{x:Type systemVM:TopMenuViewModel}" >    <Menu>      <MenuItem Header="{Binding MenuName}"                             ItemsSource="{Binding SubmenuItems}"                     ItemContainerStyle="{DynamicResource SubmenuItemStyle}" />    </Menu>  </DataTemplate>    <Menu DockPanel.Dock="Top" ItemsSource="{Binding Menus}" />

TopMenuViewModel is a collection of the menus that will appear on the menu bar. They each contain the MenuName that will be displayed and a collection called SubMenuItems that I set to be the ItemsSource.

I control the way the SubMenuItems are displayed by way of the style SumMenuItemStyle. Each SubMenuItem has its own MenuName property, Command property of type ICommand, and possibly another collection of SubMenuItems.

The result is that I am able to store all my menu information in a database and dynamically switch what menus are displayed at runtime. The entire menuitem area is clickable and displays correctly.

Hope this helps.