2

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.