WPF 上下文菜单点击路由到 WinForms 应用程序

4
我正在编写一个WPF控件,它被托管在Word VSTO AddIn(WinForms)中。现在我遇到了一个关于上下文菜单鼠标点击事件的问题。
如果我在左半部分(覆盖WinForms应用程序的部分)点击上下文菜单项,则单击事件直接传递给WinForms应用程序,我的上下文菜单无法接收该事件。
如果我点击项目的右半部分(覆盖WPF表单的部分),则一切都按预期工作。
有没有人能帮我解决这个问题?

有趣的错误!你使用的是哪个版本的.NET? - Dan Puzey
.Net Framework 4.0 客户端配置文件 - Scoregraphic
2个回答

1

1
链接已经失效,但是仍然可以通过 https://web.archive.org/ 获取。我会发布复制粘贴的答案,以节省任何可能需要它的人的时间。 - Dinac23
1
谢谢提供信息。我已经更新了存档版本的链接。 - Scoregraphic

1

这个不活跃博客的答案是:

声明一个类级别的调度器框架对象

System.Windows.Threading.DispatcherFrame _frame;

订阅GotFocusEvent和LostFocusEvent以针对菜单进行编程:

_menu.AddHandler(System.Windows.UIElement.GotFocusEvent,new RoutedEventHandler(OnGotFocusEvent));
_menu.AddHandler(System.Windows.UIElement.LostFocusEvent, new RoutedEventHandler(OnLostFocusEvent));

以下是GotFocusEvent和LostFocusEvent的事件程序实现:
private void OnGotFocusEvent(object sender, RoutedEventArgs e)
{
 if (LogicalTreeHelper.GetParent((DependencyObject)e.OriginalSource) == _menu)
  {
     Dispatcher.BeginInvoke(DispatcherPriority.Normal (DispatcherOperationCallback)delegate(object unused)
        {
         _frame = new DispatcherFrame();
         Dispatcher.PushFrame(_frame);
         return null;
        }, null);
  }
}

private void OnLostFocusEvent(object sender, RoutedEventArgs e)
{
  if (LogicalTreeHelper.GetParent((DependencyObject)e.OriginalSource) == _menu)
  {
     _frame.Continue = false;
  }
}

在我的情况下,if语句是不必要的,我像这样订阅了事件。
<EventSetter Event="GotFocus" Handler="contextMenu_GotFocus" />
<EventSetter Event="LostFocus" Handler="contextMenu_LostFocus" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接