Chao
Chao

Reputation: 73

Command doesn't work on top level MenuItem in MVVM

It works fine if the MenuItem doesn't have a sub MenuItem, like this:

<MenuItem Header="Open" Command="{Binding OpenCommand}"/>

but, when I add a sub MenuItem to it, the Command doesn't work:

<MenuItem Header="Open" Command="{Binding OpenCommand}">
    <MenuItem />
</MenuItem>

click event also doesn't work like this:

<MenuItem Header="Open" Click="MenuItem_Click">
    <MenuItem />
</MenuItem>

when I try to add the Command to the header:

<MenuItem>
    <MenuItem.Header>
        <TextBlock>
            <TextBlock.InputBindings>
                 <MouseBinding Gesture="LeftClick" Command="{Binding OpenCommand}"/>
            </TextBlock.InputBindings>
            Open
        </TextBlock>
    </MenuItem.Header>
    <MenuItem />
</MenuItem>

the Command works but the sub MenuItem doesn't show.

Any help will be appreciate, and forgive my half-baked English.

Upvotes: 0

Views: 588

Answers (1)

Onur
Onur

Reputation: 5205

If you have sub MenuItems the click event is used (and expected by the user) to show the sub-menu. To react upon a submenu opening use the event SubmenuOpened.

If you really want to be able to open a sub menu and click on the "Open", you could use this snipper, but I'd really not advice it:

<MenuItem SubmenuOpened="MenuItem_OnSubmenuOpened"> <!-- handle sub menu opening if desired -->
  <MenuItem.Header>
    <Button Click="Button_Click">Open V2</Button> <!-- handle click on "Open" if desired; doesn't open sub menu! -->
  </MenuItem.Header>
  <MenuItem />
</MenuItem>

Note that I have tested this with "Open" not being the top level menu item.

Upvotes: 1

Related Questions