首页 > 解决方案 > 如何解决显示弹出窗口的问题?

问题描述

我有一个弹出窗口,每当用户输入不允许的字符时就会出现,然后我延迟将弹出窗口在屏幕上保持 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&#x0a;characters :   \  / : * ? &quot; &lt; &gt; |"/>
        </Border>
    </Popup>

标签: c#wpfxaml

解决方案


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;
    }
}

推荐阅读