user3929476
user3929476

Reputation: 21

Creating dynamic WPF context menu

I have an ObservableCollection in my ViewModel and I want to create a ContextMenu which is bindded to that collection where every item in the collection has a submenu and all submenus are the same. For example the collection is {10,20,30} and the submenu is - Param (MenuItem) - Set (MenuItem) - Reset (MenuItem) - Clear (MenuItem) so that the final context menu would look something like this\ - 10 - Param - Set - Reset - Clear - 20 - Param - Set - Reset - Clear - 30 .... I've tried creating a resource

<x:Array x:Key="MenuResource" Type=Control>
  <MenuItem Header="Param"/>
    <MenuItem Header="Set"/>
    <MenuItem Header="Reset"/>
  <MenuItem Header="Clear"/>  
</x:Array>

and setting to ItemSource Property in MenuItem Style of the ItemContainerStyle of the ContextMenu. Nothing seems to work.

Can someone please show me the XAML way to do this. Thanks

Upvotes: 2

Views: 4469

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81313

You have to define HierarchicalDataTemplate to bind child collection and directly bind outer collection to ItemsSource of Context menu like this:

<TextBlock Text="Context menu test">
    <TextBlock.ContextMenu>
        <ContextMenu ItemsSource="{Binding YourCollection}">
            <ContextMenu.ItemTemplate>
                <HierarchicalDataTemplate
                         ItemsSource="{Binding ChildCollection}">
                    <TextBlock Text="{Binding Name}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </ContextMenu.ItemTemplate>
        </ContextMenu>
    </TextBlock.ContextMenu>
</TextBlock>

Assuming Name is a property in your underlying source object.

Upvotes: 1

Related Questions