Sunday, May 1, 2011

Is there a way to programatically close a menuitem in 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>

Thanks, Jon

From stackoverflow
  • Get hold of the MenuItem and do:

    _menuItem.IsSubmenuOpen = false;
    

    Easy way to get hold of it:

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

    Code-behind:

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

    HTH, Kent

    Jon Kragh : That did it :) Thanks!

0 comments:

Post a Comment