Search code examples
c#wpftimerdispatchertimer

WPF C# - Timer countdown


How can I implement the following in my piece of code written in WPF C#?

I have a ElementFlow control in which I have implemented a SelectionChanged event which (by definition) fires up a specific event when the control's item selection has changed.

What I would like it to do is:

  1. Start a timer
  2. If the timer reaches 2 seconds then launch a MessageBox saying ("Hi there") for example
  3. If the selection changes before the timer reaches 2 seconds then the timer should be reset and started over again.

This is to ensure that the lengthy action only launches if the selection has not changed within 2 seconds but I am not familiar with the DispatcherTimer feature of WPF as i am more in the know when it comes to the normal Timer of Windows Forms.


Solution

  • I've figured the complete code out as such:

    DispatcherTimer _timer;
    
    public MainWindow()
    {
        _myTimer = new DispatcherTimer();
        _myTimer.Tick += MyTimerTick;
        _myTimer.Interval = new TimeSpan(0,0,0,1);
    }
    
    private void ElementFlowSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        _counter = 0;
        _myTimer.Stop();
        _myTimer.Interval = new TimeSpan(0, 0, 0, 1);
        _myTimer.Start();
    }
    
    private int _counter;
    public int Counter
    {
        get { return _counter; }
        set
            {
                _counter = value;
                OnPropertyChanged("Counter");
            }
    }
    private void MyTimerTick(object sender, EventArgs e)
    {
        Counter++;
        if (Counter == 2)
        {
            _myTimer.Stop();
            MessageBox.Show(“Reached the 2 second countdown”);
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler e = PropertyChanged;
        if (e != null)
            {
                e(this, new PropertyChangedEventArgs(propertyName));
    }
    }