contextMenu menuItem中的按钮

时间:2016-10-31 18:14:16

标签: wpf menu contextmenu

我遇到了问题 - 在代码背后我添加了MenuItems的集合,其中一个StackPanel为其HeaderButtonStackPanel应该关闭整个ContextMenu,但遗憾的是它并没有。任何帮助将不胜感激。

代码示例:

var itemB = new MenuItem();
var stackPanel = new StackPanel() { Orientation = Orientation.Horizontal };
var textBox = new TextBox() { Width = 60 };
var button = new Button() { Content = "Ok", Width = 60 };
stackPanel.Children.Add(textBox);
stackPanel.Children.Add(button);
itemB.Header = stackPanel;

//1st approach - doesn't work, I can only get access to MenuItem Header
button.Click += (sender, e) =>
{
    FrameworkElement fe = sender as FrameworkElement;
    while (fe != null)
    {
        if (fe is ContextMenu)
        {
            (fe as ContextMenu).IsOpen = false;
            break;
        }
        fe = fe.Parent as FrameworkElement;
    }
};

//2nd approach - doesn't work, I can only get access to MenuItem Header
itemB.PreviewMouseUp += (sender, e) =>
{
    ((MenuItem)((MenuItem)sender).Parent).IsSubmenuOpen = false;
};

我找到了类似的文章,但没有成功:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/17603d7e-b76b-45b5-a2df-2f3b378b690c/force-button-inside-contextmenu-to-close-contextmenu?forum=wpf

WPF: button inside MenuItem, closing the menu

Is there a way to programatically close a menuitem in WPF

1 个答案:

答案 0 :(得分:0)

你说ContextMenu是在XAML上定义的,所以让我们假设像这样的代码:

<Grid>
  <Grid.ContextMenu>
    <!-- ContextMenu with a Name to be called! -->
    <ContextMenu Name="GridContextMenu"/>
  </Grid.ContextMenu>
  <Button Content="Open Menu" Click="Button_Click"/>
  <!-- other controls ... -->
</Grid>

让我们实现点击事件:

private void Button_Click(object sender, RoutedEventArgs e)
{
    var textBox = new TextBox { Width = 60 };

    var button = new Button { Content = "Ok", Width = 60 };

    var stackPanel = new StackPanel
    {
        Orientation = Orientation.Horizontal,
        Children = { textBox, button },
    };

    var menuItem = new MenuItem
    {
        Header = stackPanel,
    };

    button.Click += (s, args) =>
    {
        GridContextMenu.IsOpen = false;
        GridContextMenu.Items.Remove(menuItem);
    };

    GridContextMenu.Items.Add(menuItem);

    GridContextMenu.IsOpen = true;
}