WPF Merge parent and child context menus

Viewed 53

My ListView has ContextMenu with some options. There are some TextBlocks inside ListView with their own ContextMenus, when I right click on TextBlock, only TextBlock's ContextMenu appears. How can I show ListView options merged with TextBlock options?

Code Example:

<ListView>
    <ListView.ContextMenu>
        <ContextMenu>
            <MenuItem Header="List option"/>
        </ContextMenu>
    </ListView.ContextMenu>
    <ListViewItem>
        <TextBlock Text="Text">
            <TextBlock.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="TextBlock option"/>
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>
    </ListViewItem>
</ListView>
1 Answers

I don't know if this is the right approach, but you can sync the context menu items in the loaded event of the textblocks contextmenu. You need to build every new context menu item from scratch, you can't just merge them.

Private Sub ContextMenu_Loaded(sender As Object, e As RoutedEventArgs)
    Dim textblockContextmenu As ContextMenu = sender

    For Each item As MenuItem In lst.ContextMenu.Items
        Dim newitem As New MenuItem
        newitem.Header = item.Header
        If Not textblockContextmenu.Items.OfType(Of MenuItem)().Select(Of String)(Function(x) x.Header).Contains(item.Header) Then
            textblockContextmenu.Items.Add(newitem)
        End If
    Next
End Sub
Related