I have a scenario in which I need to have both static and dynamic menu items. The static items will be defined in XAML and the dynamic ones supplied by a View Model. Each dynamic item will itself be represented by a VieModel, lets call it a CommandViewModel. A CommandViewModel has amongst other things a display name, it can also contain other CommandViewModels.
The MainViewModel that gets used as the datacontext for the menu is as follows:
public class MainMenuViewModel : INotifyPropertyChanged
{
private ObservableCollection<CommandViewModel> m_CommandVMList;
public MainMenuViewModel()
{
m_ CommandVMList = new ObservableCollection<CommandViewModel>();
CommandViewModel cmv = new CommandViewModel();
cmv.DisplayName = "Dynamic Menu 1";
m_CommandVMList.Add(cmv);
cmv = new CommandViewModel();
cmv.DisplayName = "Dynamic Menu 2";
m_CommandVMList.Add(cmv);
cmv = new CommandViewModel();
cmv.DisplayName = "Dynamic Menu 3";
m_CommandVMList.Add(cmv);
}
public ObservableCollection<CommandViewModel> CommandList
{
get { return m_CommandVMList; }
set
{
m_CommandVMList = value;
OnPropertyChanged("CommandList");
}
}
… … …
The Menu XAML:
<Grid>
<Grid.Resources>
<HierarchicalDataTemplate DataType="{x:Type Fwf:CommandViewModel}" ItemsSource="{Binding Path=CommandViewModels}">
<MenuItem Header="{Binding Path=DisplayName}"/>
</HierarchicalDataTemplate>
</Grid.Resources>
<Menu VerticalAlignment="Top" HorizontalAlignment="Stretch">
<MenuItem Header="Static Top Menu Item 1">
<MenuItem Header="Static Menu Item 1"/>
<MenuItem Header="Static Menu Item 2"/>
<MenuItem Header="Static Menu Item 3"/>
<ItemsControl ItemsSource="{Binding Path= CommandList}"/>
<MenuItem Header="Static Menu Item 4"/>
</MenuItem>
</Menu>
</Grid>
All works fine except that whatever I try to represent the list of dynamic menus, in this case an ItemsControl it is being shown on the UI as ONE Menu Item conatining more menu items, so the entire collection of dynamic menu items get selected when you click on the item. The collection gets represented correctly in that each dynamic menu item is show as a menu item itself but within this bigger menu item. I think I see why as the Menu is simply creating a menu item for each of the contained items, static or dynamic it does not care. Is there a way to have each dynamic menu item be created on the same level and belonging to the parent menu item as the static ones on the example does ?