在 WPF 中,使用 Popup 也许会看到 PreviewMouseDown 事件被吃掉
因为 PreviewMouseDown 是 RoutingStrategy.Direct 路由事件,不能在多个视觉树使用,在设置 Popup 点击界面 StaysOpen=”False” 的逻辑就在下面代码
private void OnPreviewMouseButton(MouseButtonEventArgs e)
{
// We should only react to mouse buttons if we are in an auto close mode (where we have capture)
if (_cacheValid[(int)CacheBits.CaptureEngaged] && !StaysOpen)
{
Debug.Assert( Mouse.Captured == _popupRoot.Value, "_cacheValid[(int)CacheBits.CaptureEngaged] == true but Mouse.Captured != _popupRoot");
// If we got a mouse press/release and the mouse isn't on the popup (popup root), dismiss.
// When captured to subtree, source will be the captured element for events outside the popup.
if (_popupRoot.Value != null && e.OriginalSource == _popupRoot.Value)
{
// When we have capture we will get all mouse button up/down messages.
// We should close if the press was outside. The MouseButtonEventArgs don't tell whether we get this
// message because we have capture or if it was legit, so we have to do a hit test.
if (_popupRoot.Value.InputHitTest(e.GetPosition(_popupRoot.Value)) == null)
{
// The hit test didn't find any element; that means the click happened outside the popup.
SetCurrentValueInternal(IsOpenProperty, BooleanBoxes.FalseBox);
}
}
}
}
如果写一个 CheckBox 放在界面上,运行代码可以看到可以被打勾但是没有事件
在 UIElement_OnPreviewMouseDown
添加输出内容,代码如下,可以看到,没有符合预期输出
private void UIElement_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
{
Debug.WriteLine("PreviewMouseDown");
}
private void OpenPopup_OnClick(object sender, RoutedEventArgs e)
{
Popup.PlacementTarget = (UIElement) sender;
Popup.Placement = PlacementMode.Mouse;
Popup.IsOpen = true;
}
Original: https://www.cnblogs.com/lindexi/p/16733246.html
Author: lindexi
Title: WPF 已知问题 Popup 吃掉 PreviewMouseDown 事件
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/577732/
转载文章受原作者版权保护。转载请注明原作者出处!