C# WPF MVVM模式 倒计时功能 使用事件通知所有订阅了该事件的视图进行秒数的更新

时间:2025-04-08 06:55:50

1,创建静态倒计时类 

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

        //使用配置文件统一倒计时秒数

        public static string settingValue =           ["ReturnHomepage"];

        // 事件,用于通知秒数变化  
        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();
            }
        }

        // 触发SecondsChanged事件  
        private static void OnSecondsChanged(int seconds)
        {
            SecondsChanged?.Invoke(seconds);
        }
    }

2,在ViewModel中订阅事件 

  public class TicketInquiryViewModel : BaseViewModel
    {

        public TicketInquiryViewModel()
        {
            // 订阅倒计时秒数变化事件  
            += UpdateSeconds;

            // 启动倒计时  
            ();
        }

        

        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)
                {
                    // 倒计时结束后的代码逻辑  
                }
            }
        }

        public BaseViewModel()
        {
           
        }

    }

3,在XAML中绑定RemainingSeconds属性 

    <TextBlock ="3" Text="{Binding RemainingSeconds,StringFormat=' {0}秒之后返回首页'}"  FontSize="15" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="0,0,20,0"/>