我遇到了问题 - 在代码背后我添加了MenuItems
的集合,其中一个StackPanel
为其Header
。 Button
中StackPanel
应该关闭整个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;
};
我找到了类似的文章,但没有成功:
答案 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;
}