[英]WPF ContextMenu click routed to WinForms application
我正在編寫一個 WPF 控件,它托管在 Word VSTO AddIn (WinForms) 中。 現在我在上下文菜單上的鼠標單擊事件有問題。
如果我單擊左半部分的上下文菜單項(WinForms 應用程序上方的部分),單擊將直接轉到 WinForms 應用程序,並且我的上下文菜單不會收到該事件。
如果我單擊該項目的右半部分(WPF 表單上方的部分),一切都會按預期進行。
有人可以幫我解決這個問題嗎?
經過一些深入的研究,我偶然發現了以下錯誤:
它適用於 Excel 2007,但仍適用於其他 Office 產品(2007、2010)。 我設法使用此處描述的方法解決了我的問題:
來自非活躍博客的答案是:
聲明一個類級別的調度器框架對象
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.