我有一个弹出窗口,每当用户键入不允许的字符时,就会弹出一个窗口,然后我将延迟时间保持在屏幕上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>
答案 0 :(得分:1)
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;
}
}