Just a group of people asked how to write a timer, just I do not know, wrote a demo, and everyone to share this is the reference to the master's writing!
Timers have a good variety of writing, here to recommend a better performance, with DispatcherTimer, this demo is the countdown, the timing of the _seconds--will be changed to + + on it. Not much to say, directly on the code.
1. This is the interface, simple XAML
<GridBackground="{ThemeResource Applicationpagebackgroundthemebrush}"> <TextBlockName= "txt"HorizontalAlignment= "Center"VerticalAlignment= "Center"/> <ButtonMargin= "0,0,0,50"Content= "Start Countdown"Background= "Red"Foreground= "White"HorizontalAlignment= "Center"VerticalAlignment= "Bottom"Click= "Button_Click"/> </Grid>
2. The following is the CS code, with the DispatcherTimer, explaining the interval this property, its role is to determine the timing interval, can be in seconds, milliseconds and so on. There is also a tick delegate that is triggered when the time interval is exceeded, that is, the interval interval setting.
Public Sealed Partial classMainpage:page {PrivateDispatcherTimer _countdowntimer; Private int_seconds =Ten; PublicMainPage () { This. InitializeComponent (); } Private voidButton_Click (Objectsender, RoutedEventArgs e) { This. Countdown (); } Private voidcountdown () { This. _countdowntimer =NewDispatcherTimer (); This. _countdowntimer.interval = Timespan.fromseconds (1); This. _countdowntimer.tick + = This. _countdowntimer_tick; This. _countdowntimer.start (); } Private void_countdowntimer_tick (ObjectSenderObjecte) { This. _seconds--; Thistxt. Text = This. _seconds. ToString (); if( This. _seconds = =0) { This. Countdownstop (); } } Private voidCountdownstop () {if( This. _countdowntimer! =NULL) { This. _countdowntimer.stop (); This. _countdowntimer.tick-= This. _countdowntimer_tick; This. _countdowntimer =NULL; } } }
Refer to other people's writing, performance is very good, there is a better wording welcome comments.
C # timer notation