Reputation: 438
I have a popup that shows up whenever the user types unallowed characters, then I put a delay to hold the popup on the screen for 6 seconds, and what I want to do is that when the user types the allowed characters, then the popup should immediately disappear, and when the user types the unallowed chars again, it should show the popup and then wait for 6 seconds if the user didn't type anything. I've done it this way, But it's not working, the popup shows up, and then if I type an allowed char, it set the IsOpen
to false, but when the user types the unallowed chars again, the delay is not working anymore, it closes the popup in random seconds. How can I fix this problem, or what's the better way of doing this?
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;
}
}
This is the XAML code for popup:
<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>
Upvotes: 0
Views: 123
Reputation: 169200
Task.Delay
accepts a CancellationToken
that you can use the cancel the task on each key stroke. Something like this:
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;
}
}
Upvotes: 1