2

我有这个代码:

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)。

现在,当用户以这种方式将焦点移开时,我的弹出窗口不会关闭。有任何想法吗?

4

2 回答 2

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是您要比较的实例(您想知道它是否应该关闭)。

于 2013-02-21T23:48:37.030 回答
0

您可以添加一个 KeyDown 事件并检查是否按下了 alt+tab。

于 2013-02-21T18:45:28.680 回答