I want to create wpf countdown timer that display the result as hh:mm:ss into textbox, I would be thankful for anyone help.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
There is nothing wrong with using
DispatcherTimer
for this purpose. However, IMHO the newer TPL-basedasync
/await
paradigm makes for code that is easier to write and read. It is also better to always use good MVVM practices for WPF programs, rather than to set UI element values directly from code-behind.Here's an example of a program that implements a countdown-timer as described in the question, but using these more modern practices…
The view model is of course where the bulk of the interesting code resides, and even there the main thing is the single method
_StartCountdown()
, which implements the actual countdown:ViewModel.cs:
As noted in the comments, the above will work as-is, but if you want specific output, it's useful to have
IValueConverter
implementations to adjust the output to suit user-specific needs. Here are some examples of those:UtcToLocalConverter.cs:
TimeSpanRoundUpConverter.cs:
And of course, some XAML to define the UI (where none of the UI elements have names, nor does the code-behind need to access any of them explicitly):
MainWindow.xaml:
You can use
DispatcherTimer
class (msdn).Duration of time you can hold in
TimeSpan
structure (msdn).If you want formatting
TimeSpan
tohh:mm:ss
you should invokeToString
method with "c" argument (msdn).Example:
XAML:
Code-behind: