WPF自定义上下文菜单单击事件未触发

时间:2015-12-24 11:27:32

标签: c# wpf webbrowser-control windowsformshost

我在WindowsFormsHost中使用WebBrowser创建自定义上下文菜单。但由于某种原因,我分配给菜单项的click事件没有触发。我指定的其他事件是。

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    System.Windows.Forms.WebBrowser browser = new System.Windows.Forms.WebBrowser();
    browser.IsWebBrowserContextMenuEnabled = false;
    System.Windows.Forms.ContextMenu contextMenu = new System.Windows.Forms.ContextMenu();
    System.Windows.Forms.MenuItem menuItem = new System.Windows.Forms.MenuItem()
    {
        Text = "Add comment"
    };

    // not firing
    menuItem.Click += new EventHandler(menuItem_Click);
    // is firing
    menuItem.Select += new System.EventHandler(menuItem_Click);

    contextMenu.MenuItems.Add(menuItem);
    browser.ContextMenu = contextMenu;

    // is firing
    browser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
    // is firing
    browser.HandleCreated += new System.EventHandler(browser_HandleCreated);

    windowsFormsHost.Child = browser;
    browser.DocumentText = "Test";
}

void browser_HandleCreated(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

void browser_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
{
    throw new NotImplementedException();
}

void menuItem_Click(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

我错过了什么?

1 个答案:

答案 0 :(得分:1)

我知道这个问题很旧,但是我遇到了同样的问题。我通过使用ContextMenuStrip而不是ContextMenu对其进行了修复。

System.Windows.Forms.ContextMenuStrip webBrowserMenu = new System.Windows.Forms.ContextMenuStrip();
System.Windows.Forms.ToolStripMenuItem refreshItem = new System.Windows.Forms.ToolStripMenuItem("Refresh");
refreshItem.Click += new System.EventHandler(refreshMenuItem_Click);
webBrowserMenu.Items.Add(refreshItem);

webBrowser1.ContextMenuStrip = webBrowserMenu;