views:

45

answers:

1

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?

+3  A: 

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.

Matt Hamilton
Ugh. On closer inspection that article I linked to doesn't help that much. It has *some* extra info though, so I'll leave it in the answer.
Matt Hamilton
Ok I understand now, but is there an alternative way so I can accomplish the same thing? I don't want to have to write out the event call on all MenuItems (there will be a lot)
Jen Doran