WPF Fade out status bar text after X seconds?

Viewed 14768

I'm trying to come up with an unobtrusive way to to display minor error messages to a user. So I've added a statusbar to my form,

    <StatusBar Margin="0,288,0,0" Name="statusBar" Height="23" VerticalAlignment="Bottom">
        <TextBlock Name="statusText">Ready.</TextBlock>
    </StatusBar>

And then when they click an "Add" button, it should do some stuff, or display an error message:

private void DownloadButton_Click(object sender, RoutedEventArgs e)
{
    addressBar.Focus();
    var url = addressBar.Text.Trim();
    if (string.IsNullOrEmpty(url))
    {
        statusText.Text = "Nothing to add.";
        return;
    }
    if (!url.Contains('.'))
    {
        statusText.Text = "Invalid URL format.";
        return;
    }
    if (!Regex.IsMatch(url, @"^\w://")) url = "http://" + url;
    addressBar.Text = "";

But the message just sits there for the life of the app... I think I should reset it after about 5 seconds... how can I set a timer to do that?

Bonus: How do I give it a nifty fade-out effect as I do so?


I've created a System.Timers.Timer,

    private Timer _resetStatusTimer = new Timer(5000);

    void _resetStatusTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        statusText.Text = "Ready";
    }

But the Elapsed event runs on a different thread than the UI, which it doesn't like... how to I get around that?

3 Answers
await Task.Delay(5000); // Wait 5 seconds

for (int i = 99; i >= 0; i--)
{
    statusText.Opacity = i / 100d;

    await Task.Delay(15); // The animation will take 1.5 seconds
}

statusText.Visibility = statusText.Hidden;

statusText.Opacity = 1;

If you want to show statusText again, you have to sets it's Visibility to Visible:

statusText.Visibility = Visibility.Visible;

Also make sure to add the async modifier to your methods signature, otherwise the compiler would show you an error relating the await operator. await is used that the UI still responds while the text is fading out.

Related