You are currently viewing Auto Hide Label in WPF with C#
Auto Hide Label in WPF with C#

Auto Hide Label in WPF with C#

For auto hide Label you can use Timer. As WPF does not have a Timer control or class you can use DispatchTimer class defined in the System.Windows.

You can check Working with the Timer in WPF

Creating a DispatchTimer

The following code snippet creates a DispatchTimer object.

DispatcherTimer dispatcherTimer = new DispatcherTimer(); 
int counter = 0;

Set Label Content and Start the Timer

Set the lblmessage text and start the timer.

private void Button1_Click(object sender, RoutedEventArgs e)
{
     lblMessage.Content = "Thank you, your record inserted.";
     dispatcherTimer.Start();
}

Hide Label and Stop the Timer

On dispatcherTimer tick event we increment counter up to 5 and if the value of the counter is 5 or more then 5 then we stop the timer and hide the lblMessage label. As user point of view, when the user clicks on the button the “Thank you, your record inserted.” display for 5 seconds and automatically disappear after that.

private void dispatcherTimer_Tick(object sender, EventArgs e)
{
           if(counter ==5)
            {
                lblMessage.Visibility = Visibility.Collapsed;
                dispatcherTimer.Stop();
            }
            else
            {
                counter++;
            }
}