wpf popup点击外部后自动关闭
通过InputManager.Current.PreProcessInput在触摸事件执行前检测popup状态
如果点击在Popup外部则关闭
protected override void OnActivated(EventArgs e)
{
base.OnActivated(e);
InputManager.Current.PreProcessInput += (s, args) =>
{
if (args.StagingItem.Input is TouchEventArgs touchEvent &&
touchEvent.RoutedEvent == UIElement.PreviewTouchDownEvent)
{
var popList = new List<Popup>() { popIsFirstPage, popIsLastPage, popIsFirstQuestion, popIsLastQuestion,
popExit, popSelectPen, popSelectErase, popClass, popWrongQuestion };
foreach (var item in popList)
{
if (item.IsOpen)
{
// 判断是否点击在 Popup 外部
if (!IsTouchWithinPopup(touchEvent.GetTouchPoint(item.Child), item))
{
item.IsOpen = false;
}
}
}
}
};
}
private bool IsTouchWithinPopup(TouchPoint touchPoint, Popup popup)
{
if (popup.Child is FrameworkElement child)
{
// 获取Popup子元素的边界矩形
Rect bounds = new Rect(0, 0, child.ActualWidth, child.ActualHeight);
// 将触摸点坐标转换为相对于子元素的坐标
Point relativePoint = touchPoint.Position;
// 判断坐标是否在边界内
return bounds.Contains(relativePoint);
}
return false;
}
留待后查,同时方便他人
联系我:renhanlinbsl@163.com
联系我:renhanlinbsl@163.com