Is there a way to programatically close a menuitem in WPF

后端 未结 3 1315
执笔经年
执笔经年 2021-01-12 06:28

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?

         


        
3条回答
  •  一生所求
    2021-01-12 07:04

    I find that using IsSubmenuOpen doesn't properly eliminate focus from the Menu containing the MenuItem (especially if the Menu is in a ToolBar - the top-level MenuItem remains Selected even though the menu is "Closed"). I find sending a MouseUp event to the MenuItem works better (in the button's, or nested control's, Click event handler):

            private void button_Click(object sender, RoutedEventArgs e) {
               Button b = sender as Button;
    
               if (b == null || !(b.Parent is MenuItem))
                  return;
    
               MenuItem mi = b.Parent as MenuItem;
    
               mi.RaiseEvent(
                  new MouseButtonEventArgs(
                     Mouse.PrimaryDevice, 0, MouseButton.Left
                  ) 
                  {RoutedEvent=Mouse.MouseUpEvent}
               );
            }
    

提交回复
热议问题