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 に答える