1
votes

I know that events in WPF bubble up the visual tree, so I don't understand why this simple example of catching the event of a context menuitem click event on it's parent listbox doesn't work:

<ListBox Width="200" MenuItem.Click="MenuItem_Click">
    <ListBoxItem>
        <TextBlock Text="Hello">
            <TextBlock.ContextMenu>
                <ContextMenu>
                     <MenuItem Header="World 1"></MenuItem>
                     <MenuItem Header="World 2"></MenuItem>
                     <MenuItem Header="World 3"></MenuItem>
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>
    </ListBoxItem>
</ListBox>

I expect that when any of the MenuItems are clicked the debugger will hit my event handler MenuItem_Click but it never does. Can anyone please explain what I'm doing wrong?

1

1 Answers

5
votes

ContextMenus (and their items) aren't technically a part of the visual tree. They aren't "children" of the item they belong to. So their events don't bubble up to their owners.

Some more information can be found here: RoutedCommands in a ContextMenu.