0

I have a Button inside a MenuItem.Header like this:

<Menu>
    <MenuItem>
        <MenuItem.Header>
            <Button>Hello</Button>
        </MenuItem.Header>
        <MenuItem Header="SubItem1"/>
        <MenuItem Header="SubItem2"/>
    </MenuItem>
</Menu>

enter image description here

if I click the MenuItem outside the Button, the sub-menu opens. But if I click the Button the sub-menu will not open. I believe that's because the event of the clicked is not passed to the MenuItem. How do I fix it?

In short - I want the sub-menu to open when clicking the Button.

(The use is mainly for styling purposes, I have a button style and I want to use it as a MenuItem)

Shachar Har-Shuv
  • 666
  • 6
  • 24

1 Answers1

2

A Button doesn't know how to expand a MenuItem unless you tell it how to by writing some code:

<Menu>
    <MenuItem>
        <MenuItem.Header>
            <Button Click="Button_Click">Hello</Button>
        </MenuItem.Header>
        <MenuItem Header="SubItem1"/>
        <MenuItem Header="SubItem2"/>
    </MenuItem>
</Menu>

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    MenuItem mi = btn.Parent as MenuItem;
    if (mi != null)
        mi.IsSubmenuOpen = !mi.IsSubmenuOpen;
}
mm8
  • 163,881
  • 10
  • 57
  • 88
  • I guess it would work but I want to avoid using code behind to sustain MVVM architecture pattern. Isn't there a general solution to pass event to parent? – Shachar Har-Shuv Mar 20 '18 at 08:05
  • "Pass event to parent" without writing some code? Certainly not. Also, how a MenuItem is expanded is not the responsibility of a view model. This is purely view-based functionality. – mm8 Mar 20 '18 at 15:34
  • Sounds logical but I've been told that in MVVM the View should only be in XAML and you shouldn't write code behind. Is that a bad paradigm? – Shachar Har-Shuv Mar 21 '18 at 10:24
  • That's not true. MVVM is not about eliminating *view-related* code from the views. It's about separatation of concerns. In fact, you could write an entire view programmatically without violating the MVVM pattern if you wanted to. But that's another story that doesn't have anything to do with your original question. – mm8 Mar 21 '18 at 14:25
  • OK! Thanks for the enlightenment. – Shachar Har-Shuv Mar 21 '18 at 20:25