Show current time WPF

后端 未结 3 587
醉话见心
醉话见心 2021-01-07 06:45

The only way to show current time updating regularly I found is to use timer. Of course, I can implement INotifyPropertyChanged and some special property to be

3条回答
  •  迷失自我
    2021-01-07 06:50

    WPF is a static markup language. As far as I am aware there is not a mechanism available in pure XAML to provide the functionally you are looking for.

    If you want to avoid using a timer directly you can abstract it away using Tasks.

    MainWindow XAML:

    
        
            
        
    
    

    Code behind:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            DataContext = new CurrentTimeViewModel();
        }
    }
    
    public class CurrentTimeViewModel : INotifyPropertyChanged
    {
        private string _currentTime;
    
        public CurrentTimeViewModel()
        {
            UpdateTime();
        }
    
        private async void UpdateTime()
        {
            CurrentTime = DateTime.Now.ToString("G");
            await Task.Delay(1000);
            UpdateTime();
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    
        public string CurrentTime
        {
            get { return _currentTime; }
            set { _currentTime = value; OnPropertyChanged(); }
        }
    }
    

    This is probably one of the more succinct and certainly as "Modern" WPF you are going to get.

提交回复
热议问题