Shah Newaj Shah Newaj - 2 years ago 104
C# Question

Showing a label for 3/5 seconds in wpf C# but after some click it doesn't stay that longer

I'm trying to show text in a label in wpf when a button is pressed and then hide after couple of seconds. I know there are answers of this, but my problem is different.

I used these 2 ways for hiding the label:


//When the button is pressed
label_plus.Visibility = System.Windows.Visibility.Visible;

DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 5);
timer.Tick += timer_Tick; //Or, timer.Tick += new EventHandler(timer_Tick);

// The timer event handler
void timer_Tick(object sender, EventArgs e)
label_plus.Visibility = System.Windows.Visibility.Collapsed;


//Button pressed
label_plus.Content = label_plus1.Content = "+";
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 5);
timer.Tick += (o, args) => label_plus.Content = "";

Note: I the second one is almost same, except the "timer.tick += (o, args)" line. I got this code from: Here. It was a Form application code, so I just tried that part and it worked.

The 1st code I got directly from here.

The problem is this both works pretty well on 1st and second time. And maybe 3rd. But after that I feel like the timer second is decreasing. After 2/3 times, it hides within 3/4 seconds, after that it barely stays for 1 second or less.

Is there a better way to do this or getting rid of this problem?
I'm new in Visual Studio.

This also works well, but keeps repeating. Any way to stop after one process?

var timer = new System.Timers.Timer();

timer.Elapsed += timer_Tick;
timer.Interval = 3000;
timer.Enabled = true;

void timer_Tick(object sender, EventArgs e)
//label_plus.Visibility = label_plus1.Visibility = System.Windows.Visibility.Collapsed;
MessageBox.Show("Show some data");


Thanks in advance.

Answer Source

This works:


    <Button Width="50"
            Content="OK" />
    <Label x:Name="MyLabel"
            Content="THIS IS A LABEL"
            Visibility="Collapsed" />


private DispatcherTimer dispatcherTimer;

public MainWindow()

    //Create a timer with interval of 2 secs
    dispatcherTimer = new DispatcherTimer();
    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
    dispatcherTimer.Interval = new TimeSpan(0, 0, 2);

private void Button_Click(object sender, RoutedEventArgs e)
    //Things which happen before the timer starts
    MyLabel.Visibility = System.Windows.Visibility.Visible;

    //Start the timer

private void dispatcherTimer_Tick(object sender, EventArgs e)
    //Things which happen after 1 timer interval
    MessageBox.Show("Show some data");
    MyLabel.Visibility = System.Windows.Visibility.Collapsed;

    //Disable the timer
    dispatcherTimer.IsEnabled = false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download