我有这段代码:
Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this,
OnMouseDownOutsideCapture);
当我的WPF弹出窗口外发生鼠标点击时,它会完全捕获(所以我可以关闭它)。
private void OnMouseDownOutsideCapture(object sender, MouseButtonEventArgs e)
{
if (Mouse.Captured is ComboBox) return;
if (IsOpen)
IsOpen = false;
ReleaseMouseCapture();
}
但我需要一些方法来了解焦点是否通过键盘移动到弹出窗口之外。更具体地说,通过快捷方式(即Alt + T)。
现在,当用户将焦点移开时,我的弹出窗口不会关闭。有什么想法吗?
答案 0 :(得分:1)
我就这样做了:
将其添加到构造函数:
EventManager.RegisterClassHandler(typeof(UIElement),
Keyboard.PreviewGotKeyboardFocusEvent,
(KeyboardFocusChangedEventHandler)OnPreviewAnyControlGotKeyboardFocus);
然后添加此事件处理程序:
/// <summary>
/// When focus is lost, make sure that we close the popup if needed.
/// </summary>
private void OnPreviewAnyControlGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
// If we are not open then we are done. No need to go further
if (!IsOpen) return;
// See if our new control is on a popup
var popupParent = VLTreeWalker.FindParentControl<Popup>((DependencyObject)e.NewFocus);
// If the new control is not the same popup in our current instance then we want to close.
if ((popupParent == null) || (this.popup != popupParent))
{
popupParent.IsOpen = false;
}
}
VLTreeWalker是一个自定义类,它在可视化树中查找与传入的泛型类型匹配,然后(如果找不到匹配项,则会向上走逻辑树。)可悲的是,我不能很容易在这里发布消息来源。
this.popup
是您要比较的实例(您想知道它是否应该关闭)。
答案 1 :(得分:0)
您可以添加KeyDown事件并检查是否按下了alt + tab。