WinUI 3:在点击弹出框和文本框之外时关闭弹出框
我有一个 TextBox,被点击时会打开一个 Popup。
如果我点击在 TextBox 外部且在 Popup 外部的任意区域,我想让 Popup 消失。
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
namespace some_namespace;
public sealed partial class Foo : Window
{
public Foo()
{
InitializeComponent();
}
private void SearchBox_GotFocus(object sender, RoutedEventArgs e)
{
ResultsPopup.IsOpen = true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<Window
x:Class="some_namespace.Foo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Padding="100">
<Grid x:Name="SearchBarRoot" VerticalAlignment="Top" Width="300">
<TextBox x:Name="SearchBox"
PlaceholderText="type here"
GotFocus="SearchBox_GotFocus" />
<Popup x:Name="ResultsPopup" VerticalOffset="40">
<Border Width="300" Height="150" Background="LightGray">
<TextBlock Text="results" Margin="12" />
</Border>
</Popup>
</Grid>
</Grid>
</Window>
提示:这是一个WinUI 3 C#项目,不是WPF或 UWP。
而且,不,IsLightDismissEnabled="True" 在 Popup 上并没有奏效。它把对 TextBox 的点击当作要让它消失的操作。
另外,当 TextBox 失去焦点时,我也不能隐藏 Popup。如果我这么做,Popup 会在我点击它的瞬间消失,因为点击它会把焦点从 TextBox 移走。
解决方案
你可以使用 Tapped 事件。同时,确保把 Background 设置为 Tranparent,或设置为其他任意颜色,这样 Tapped 事件才会起作用。
<Grid
x:Name="RootGrid"
Padding="100"
Background="Transparent"
Tapped="RootGrid_Tapped">
<Grid x:Name="SearchBarRoot"
Width="300"
VerticalAlignment="Top">
<TextBox x:Name="SearchBox"
GotFocus="SearchBox_GotFocus"
PlaceholderText="type here" />
<Popup x:Name="ResultsPopup" VerticalOffset="40">
<Border x:Name="PopupBorder"
Width="300"
Height="150"
Background="LightGray">
<TextBlock Margin="12" Text="results" />
</Border>
</Popup>
</Grid>
</Grid>
private void RootGrid_Tapped(object sender, TappedRoutedEventArgs e)
{
ResultsPopup.IsOpen = false;
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。