这个不活跃博客的答案是:
声明一个类级别的调度器框架对象
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" />