Show current time WPF

后端 未结 3 610
醉话见心
醉话见心 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:57

    Here is a little code sample that works without a timer:

    public DateTime CurrentTime
    {
        get => DateTime.Now;
    }
    
    public CurrentViewModelTime(object sender, RoutedEventArgs e)
    {
        _ = Update(); // calling an async function we do not want to await
    }
    
    private async Task Update()
    {
        while (true)
        {
            await Task.Delay(100);
            OnPropertyChanged(nameof(CurrentTime)));
        }
    }
    

    Of course, this Update() function never returns, but it does its loop on a threadpool thread and does not even block any thread for long.

    You can perfectly also implement this in the window directly without a viewmodel.

提交回复
热议问题