wpf 为什么不显示 ContextMenu(弹出菜单)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12099282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does not the ContextMenu(popup menu) show up?
提问by user1298925
The following class derives from System.Windows.Controls.UserControl. In said class I call OpenFileDialogto open a XAML file (workflow file). Next, I implement a dynamic menu when right clicking the mouse. The menu does not show up. Is this a threading problem or a UI problem? In my research I've been unable to discover a solution.
以下类派生自System.Windows.Controls.UserControl. 在上述课程中,我调用OpenFileDialog打开一个 XAML 文件(工作流文件)。接下来,我在鼠标右键单击时实现了一个动态菜单。菜单不显示。这是线程问题还是UI问题?在我的研究中,我一直无法找到解决方案。
Thanks in advance.
提前致谢。
private void File_Open_Click(object sender, RoutedEventArgs e)
{
var fileDialog = new OpenFileDialog();
fileDialog.Title = "Open Workflow";
fileDialog.Filter = "Workflow| *.xaml";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
LoadWorkflow(fileDialog.FileName);
MouseDown += new System.Windows.Input.MouseButtonEventHandler(mouseClickedResponse);
}
}
private void mouseClickedResponse(object sender, System.Windows.Input.MouseEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
LoadMenuItems();
}
}
private void LoadMenuItems()
{
System.Windows.Controls.ContextMenu contextmenu = new System.Windows.Controls.ContextMenu();
System.Windows.Controls.MenuItem item1 = new System.Windows.Controls.MenuItem();
item1.Header = "A new Test";
contextmenu.Items.Add(item1);
this.ContextMenu = contextmenu;
this.ContextMenu.Visibility = Visibility.Visible;
}
回答by Dunstad
Came across this problem myself, I used this:
自己遇到了这个问题,我使用了这个:
ContextMenu.IsOpen = true;
回答by flix
you have to call the ContextMenu's Show(Control, Point) method. furthermore i wouldn't instantiate a new context menu each time the control is clicked, instead i would do something like that:
您必须调用 ContextMenu 的Show(Control, Point)方法。此外,每次单击控件时,我都不会实例化新的上下文菜单,而是会执行以下操作:
MyClass()
{
// create the context menu in the constructor:
this.ContextMenu = new System.Windows.Forms.ContextMenu();
System.Windows.Forms.MenuItem item1 = new System.Windows.Forms.MenuItem();
item1.Text = "A new Test";
this.ContextMenu.Items.Add(item1);
}
private void mouseClickedResponse(object sender, System.Windows.Input.MouseEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
// show the context menu as soon as the right mouse button is pressed
this.ContextMenu.Show(this, e.Location);
}
}
回答by DGH
I think you need to call contextMenu.Show
我想你需要打电话 contextMenu.Show

