Shachar Har-Shuv
Shachar Har-Shuv

Reputation: 822

Button inside a MenuItem won't open Sub-MenuItems

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)

Upvotes: 0

Views: 671

Answers (2)

56ka
56ka

Reputation: 1565

Here is my solution (I have MaterialDesignInXAML activated so it looks different but it's the same).

I did it the reverse way of your example: create a button detached of the menu and hide the menu itself.


<StackPanel Orientation="Horizontal">
    <Menu>
        <!-- Set width=0 to hide the menu -->
        <MenuItem Width="0" x:Name="myMenu">
            <MenuItem Header="Settings"/>
            <MenuItem Header="Exit"/>
        </MenuItem>
    </Menu>
    <Button Content="Try me">
        <b:Interaction.Triggers>
            <b:EventTrigger EventName="Click">
                <b:ChangePropertyAction TargetObject="{Binding ElementName=myMenu}" PropertyName="IsSubmenuOpen" Value="True"/>
            </b:EventTrigger>
        </b:Interaction.Triggers>
    </Button>
</StackPanel>

enter image description here

Upvotes: 0

mm8
mm8

Reputation: 169200

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;
}

Upvotes: 2

Related Questions