解决方法
您可以使用DispatcherTimer类(
msdn).
TimeSpace结构的持续时间(msdn).
如果要格式化TimeSpan到hh:mm:ss,您应该使用“c”参数(msdn)调用ToString方法.
例:
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>
代码隐藏:
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,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(); } } }