c# - 如何解决显示弹出窗口的问题?
问题描述
我有一个弹出窗口,每当用户输入不允许的字符时就会出现,然后我延迟将弹出窗口在屏幕上保持 6 秒,我想要做的是当用户输入允许的字符时,弹出窗口应该立即消失,当用户再次输入不允许的字符时,它应该显示弹出窗口,如果用户没有输入任何内容,则等待 6 秒。我已经这样做了,但它不起作用,弹出窗口出现,然后如果我输入允许的字符,它将设置IsOpen
为 false,但是当用户再次输入不允许的字符时,延迟不再起作用,它会在随机秒内关闭弹出窗口。我该如何解决这个问题,或者有什么更好的方法?
private async void txtName_TextChanged(object sender, EventArgs e)
{
if (Regex.IsMatch(txtName.Text, @"[\\/:*?""<>|]"))
{
string pattern = @"[\\/:*?""<>|]";
Regex regex = new Regex(pattern);
txtName.Text = regex.Replace(txtName.Text, "");
if (AlertPopup.IsOpen == false)
{
AlertPopup.IsOpen = true;
await Task.Delay(6000); //It stays true for 6 seconds
AlertPopup.IsOpen = false;
}
}
else
{
AlertPopup.IsOpen = false;
}
}
这是弹出窗口的 XAML 代码:
<Popup AllowsTransparency="True" PlacementTarget="{Binding ElementName=txtName}"
Placement="Bottom" x:Name="AlertPopup">
<Border Margin="0,0,35,35" Background="#272C30" BorderBrush="#6C757D"
BorderThickness="2" CornerRadius="10">
<Border.Effect>
<DropShadowEffect Color="Black" BlurRadius="35" Direction="315"
ShadowDepth="16" Opacity="0.2"/>
</Border.Effect>
<TextBlock Padding="8,3,8,5" Foreground="#ADB5BD" Background="Transparent" FontSize="12"
Text="The file name can't contain any of the following
characters : \ / : * ? " < > |"/>
</Border>
</Popup>
解决方案
Task.Delay
接受一个CancellationToken
,您可以在每次击键时使用取消任务。像这样的东西:
private CancellationTokenSource cts;
private async void txtName_TextChanged(object sender, EventArgs e)
{
if (cts != null)
{
cts.Cancel();
cts.Dispose();
}
cts = new CancellationTokenSource();
if (Regex.IsMatch(txtName.Text, @"[\\/:*?""<>|]"))
{
string pattern = @"[\\/:*?""<>|]";
Regex regex = new Regex(pattern);
txtName.TextChanged -= txtName_TextChanged;
txtName.Text = regex.Replace(txtName.Text, "");
txtName.TextChanged += txtName_TextChanged;
if (AlertPopup.IsOpen == false)
{
AlertPopup.IsOpen = true;
try
{
await Task.Delay(6000, cts.Token);
}
catch (TaskCanceledException) { }
finally
{
AlertPopup.IsOpen = false;
}
}
}
else
{
AlertPopup.IsOpen = false;
}
}
推荐阅读
- php - 将相同商品添加到购物车时如何在会话中更新产品数量?
- python - 使用 python flask_mail msg.body="" 通过电子邮件发送多个 html 表单字段的数据
- caching - Gitlab CI 在每个作业使用后再次保存缓存
- reactjs - Botframework Create Directline 从服务器获取令牌
- reactjs - 基本待办事项项目中的“DELETE_TODO”
- excel - 检查小时列是否存在所有时间
- spring-boot - WebLogic Server 中未启动 Spring Web MVC
- angularjs - 无法使用 handlererror 重定向
- sql - 如何为工作时间创建 SQL 查询
- c# - 如何更改 RectTransform 的锚点以更改面板的宽度?