如何让一个WPF倒计时? [英] How to make a wpf countdown timer?
本文介绍了如何让一个WPF倒计时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要创建一个显示结果为 HH WPF倒计时:MM:SS 到文本框,我会感谢任何人的帮助。
I want to create wpf countdown timer that display the result as hh:mm:ss into textbox, I would be thankful for anyone help.
推荐答案
您可以使用 DispatcherTimer
类(的 MSDN )
持续时间时间,你可以在时间跨度持有
结构( MSDN 。)
Duration of time you can hold in TimeSpan
structure (msdn).
如果你想格式化时间跨度
到 HH:MM: SS
您应该调用的ToString
方法以C参数(的msdn )
If you want formatting TimeSpan
to hh:mm:ss
you should invoke ToString
method with "c" argument (msdn).
例如:
XAML:
<Window x:Class="CountdownTimer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Name="tbTime" />
</Grid>
</Window>
代码隐藏:
Code-behind:
using System;
using System.Windows;
using System.Windows.Threading;
namespace CountdownTimer
{
public partial class MainWindow : Window
{
DispatcherTimer _timer;
TimeSpan _time;
public MainWindow()
{
InitializeComponent();
_time = TimeSpan.FromSeconds(10);
_timer = new DispatcherTimer(new TimeSpan(0, 0, 1), DispatcherPriority.Normal, delegate
{
tbTime.Text = _time.ToString("c");
if (_time == TimeSpan.Zero) _timer.Stop();
_time = _time.Add(TimeSpan.FromSeconds(-1));
}, Application.Current.Dispatcher);
_timer.Start();
}
}
}
这篇关于如何让一个WPF倒计时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文