web123456

C# WPF MVVM mode Countdown function Use events to notify all views subscribed to the event for updates in seconds

1. Create a static countdown class

 public static class CountdownManager
    {
        private static DispatcherTimer _timer;
        private static int _seconds;

//Use configuration file to uniformly count down seconds

        public static string settingValue =           ["ReturnHomepage"];

// Event, used to notify the number of seconds changes
        public static event Action<int> SecondsChanged;

        static CountdownManager()
        {
            _timer = new DispatcherTimer();
            _timer.Interval = (1);
            _timer.Tick += Timer_Tick;
        }

        public static void Start()
        {
            _seconds = Convert.ToInt32(settingValue);
            _timer.Start();
        }

        public static void Stop()
        {
            _timer.Stop();
        }

        private static void Timer_Tick(object sender, EventArgs e)
        {
            if (_seconds > 0)
            {
                _seconds--;
                OnSecondsChanged(_seconds);
            }
            else
            {
                Stop();
            }
        }

// Trigger SecondsChanged event
        private static void OnSecondsChanged(int seconds)
        {
            SecondsChanged?.Invoke(seconds);
        }
    }

2. Subscribe to events in ViewModel

  public class TicketInquiryViewModel : BaseViewModel
    {

        public TicketInquiryViewModel()
        {
// Subscribe to countdown seconds change event
            += UpdateSeconds;

// Start countdown
            ();
        }

        

        private void UpdateSeconds(int seconds)
        {
            RemainingSeconds = seconds;
        }

}

 public class BaseViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }


        public int _remainingSeconds;
        public int RemainingSeconds
        {
            get { return _remainingSeconds; }
            set
            {
                if (_remainingSeconds == value) return;
                _remainingSeconds = value;
                OnPropertyChanged("RemainingSeconds");
                if (_remainingSeconds <= 0)
                {
                    // Code logic after countdown  
                }
            }
        }

        public BaseViewModel()
        {
           
        }

    }

3. Bind the RemainingSeconds property in XAML

<TextBlock ="3" Text="{Binding RemainingSeconds,StringFormat=' Return to homepage after {0} seconds'}"  FontSize="15" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,20,0"/>