我正在为我正在从事的项目实施计时器。每当按下按钮时都会触发计时器。
第一次按下时,它会设置定时器的持续时间,然后启动定时器。每当计时器滴答时,程序就会减少持续时间并将其打印到屏幕上。它工作得很好......直到你在计时器运行时再次按下按钮。当您执行此操作时,tick 事件中的操作会发生您在按钮运行时按下按钮的次数。
我的 XAML 看起来像这样。
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock x:Name="tBox" Text="TIMER" Grid.Row="0" HorizontalAlignment="Center" Style="{StaticResource PhoneTextTitle2Style}"/>
<TextBlock x:Name="timer" Text="00" Grid.Row="1" HorizontalAlignment="Center" Style="{StaticResource PhoneTextTitle1Style}"/>
</Grid>
<Button
Grid.Row="1"
Grid.Column="0"
Content="Online"
HorizontalAlignment="Center"
Width="200"
Height="75" Click="trigger" />
我的 C# 看起来像这样:
public partial class MainPage : PhoneApplicationPage
{
int duration = 0;
int converted = 0;
int count = 0;
DispatcherTimer tmr = new DispatcherTimer();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void trigger(object sender, RoutedEventArgs e)
{
resetTimer();
timer.Text = "30";
tmr.Interval = TimeSpan.FromSeconds(1);
tmr.Tick += OnTimerTick;
tmr.Start();
}
void OnTimerTick(object sender, EventArgs args)
{
converted = duration - 1;
timer.Text = converted.ToString();
duration = converted;
tBox.Text = strConvert;
count = count + 1;
if (duration == 0)
{
tmr.Stop();
}
}
void resetTimer()
{
count = 0;
DispatcherTimer tmr = new DispatcherTimer();
tmr.Interval = TimeSpan.FromSeconds(0);
duration = 30;
converted = 0;
tmr.Stop();
}
}