剛才一個交流群里有人問計時器怎么寫,正好我也不太熟,就寫了個demo,和大家分享一下這個是參考師傅的寫的!
計時器有好多種寫法,這里給大家推薦一個性能比較好的,用dispatchertimer做的,本demo是倒計時的,計時的將_seconds--改成++就可以了。不多說了,直接上代碼。
1.這是界面,簡單的xaml
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <TextBlock Name="txt" HorizontalAlignment="Center" VerticalAlignment="Center"/> <Button Margin="0,0,0,50" Content="開始倒計時" Background="Red" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="Button_Click"/> </Grid>
2.下面是cs代碼,用的dispatchertimer,解釋下Interval這個屬性,它的作用是確定計時間隔,可以用秒、毫秒之類的。還有個Tick委托,該委托是在超過計時間隔時觸發的,也就是Interval的時間間隔設置。
public sealed partial class MainPage : Page { private DispatcherTimer _countDownTimer; private int _seconds = 10; public MainPage() { this.InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { this.CountDown(); } private void CountDown() { this._countDownTimer = new DispatcherTimer(); this._countDownTimer.Interval = TimeSpan.FromSeconds(1); this._countDownTimer.Tick += this._countDownTimer_Tick; this._countDownTimer.Start(); } private void _countDownTimer_Tick(object sender, object e) { this._seconds--; this.txt.Text = this._seconds.ToString(); if (this._seconds == 0) { this.CountDownStop(); } } private void CountDownStop() { if (this._countDownTimer != null) { this._countDownTimer.Stop(); this._countDownTimer.Tick -= this._countDownTimer_Tick; this._countDownTimer = null; } } }
參考別人的寫法寫的,性能上還是很優異,有更好的寫法歡迎評論。