簡體   English   中英

WPF ContextMenu 單擊路由到 WinForms 應用程序

[英]WPF ContextMenu click routed to WinForms application

我正在編寫一個 WPF 控件,它托管在 Word VSTO AddIn (WinForms) 中。 現在我在上下文菜單上的鼠標單擊事件有問題。

如果我單擊左半部分的上下文菜單項(WinForms 應用程序上方的部分),單擊將直接轉到 WinForms 應用程序,並且我的上下文菜單不會收到該事件。

如果我單擊該項目的右半部分(WPF 表單上方的部分),一切都會按預期進行。

說明問題

有人可以幫我解決這個問題嗎?

來自非活躍博客的答案是:

聲明一個類級別的調度器框架對象

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" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM