有没有办法以编程方式关闭WPF中的菜单项

有没有办法以编程方式关闭WPF中的菜单项

问题描述:

我在wpf中有一个菜单,上面有一个输入框和一个按钮.用户单击按钮后,我需要关闭菜单.

I have a menu in wpf that has an input box and a button on it. Once the user clicks the button I need to close the menu.

有没有办法做到这一点?

Is there a way to do this?

    <Menu x:Name="MainMenu">
        <MenuItem Header="Main">
            <MenuItem Header="SubMenu" x:Name="SubMenu">
                <StackPanel Orientation="Horizontal">
                    <TextBox Width="50" x:Name="TextBox" />
                    <Button Content="Click Me and Close" x:Name="Button" IsDefault="True"/>
                </StackPanel>
            </MenuItem>
        </MenuItem>

谢谢, 乔恩

掌握MenuItem并执行:

_menuItem.IsSubmenuOpen = false;

轻松掌握它的方法:

<Button x:Name="_button" Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}, AncestorLevel=2}"/>

隐藏代码:

_button.Click += delegate
{
    (_button.Tag as MenuItem).IsSubmenuOpen = false;
};