为什么不显示ContextMenu(弹出菜单)?
以下班级来自System.Windows.Controls.UserControl
。在上述课程中我打电话OpenFileDialog
打开一个XAML文件(工作流文件)。接下来,我右键单击鼠标时实现一个动态菜单。菜单不显示。这是线程问题还是UI问题?在我的研究中,我一直无法找到解决方案。为什么不显示ContextMenu(弹出菜单)?
在此先感谢。
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;
}
你必须调用文本菜单的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);
}
}
感谢您的回复。但在我的情况this.ContextMenu没有Show方法。我在“Show”下面看到红线,并且它不能编译。然而,我在我的代码中使用system.Windows.Controls。难道我需要使用不同的组件或不同版本? – user1298925
我也试过你的解决方案,它不工作可能一个原因是我不能使用你的代码这行:this.ContextMenu.Show(this,e.Location); 我很乐意提供建议,再次感谢 – user1298925
对不起,我刚刚意识到您使用的是Windows Presentation Foundation,而不是Windows Forms。 WPF ContextMenu没有Show方法。我不熟悉WPF,但是[http://wpftutorial.net/ContextMenu.html](http://wpftutorial.net/ContextMenu.html)可以帮助你。这个[ContextMenu](http://msdn.microsoft.com/de-de/library/system.windows.controls.contextmenu)是你的类的正确文档页面。 – flix
您必须在单击之前添加ContextMenu。 ContextMenu使用您绑定它的任何内容作为PlacementTarget。 ContextMenus在点击时被触发,而不是在点击之后触发,这就是为什么什么都没有出现。您始终可以设置上下文菜单,然后将UserControl.ContextMenu IsEnabled值设置为false,直到您希望它可点击。 –
鲍勃是正确的,上下文菜单必须绑定到一些父控制(使用wpf/xaml常见的行为),你不是我赢的形式,使用wpf会导致你有上下文菜单定义! – inva
感谢您的答复。我尝试了您的解决方案,但无效。 – user1298925