我有一個包含倒數計時器的 WPF 應用程式,我堅持使用它的格式化部分,我幾乎沒有編程經驗,這是我第一次使用 c#。我想使用 DispatchTimer從15 分鐘開始倒計時,但截至目前,我的計時器只從15 秒開始倒計時,有什么想法嗎?
到目前為止我的倒數計時器:
public partial class MainWindow : Window
{
private int time = 15;
private DispatcherTimer Timer;
public MainWindow()
{
InitializeComponent();
Timer = new DispatcherTimer();
Timer.Interval = new TimeSpan(0,0,1);
Timer.Tick = Timer_Tick;
Timer.Start();
}
void Timer_Tick(object sender, EventArgs e) {
if (time > 0)
{
time--;
TBCountDown.Text = string.Format("{0}:{1}", time / 60, time % 60);
}
else {
Timer.Stop();
}
}
輸出如下所示:

uj5u.com熱心網友回復:
更好的方法是使用 aTimeSpan而不是int使用數字。TimeSpan在以下應用程式中設定該值將根據需要進行倒計時。
TimeSpan.FromMinutes 幾分鐘
TimSpan.FromSeconds 幾秒鐘
您可以在此處查看更多詳細資訊。
public partial class MainWindow : Window
{
DispatcherTimer dispatcherTimer;
TimeSpan time;
public MainWindow()
{
InitializeComponent();
time = TimeSpan.FromMinutes(15);
dispatcherTimer = new DispatcherTimer();
dispatcherTimer.Interval = TimeSpan.FromSeconds(1);
dispatcherTimer.Tick = DispatcherTimer_Tick;
dispatcherTimer.Start();
}
private void DispatcherTimer_Tick(object sender, EventArgs e)
{
if (time == TimeSpan.Zero) dispatcherTimer.Stop();
else
{
time = time.Add(TimeSpan.FromSeconds(-1));
MyTime.Text = time.ToString("c");
}
}
}
Xaml 代碼
<Grid>
<TextBlock Name="MyTime" />
</Grid>
uj5u.com熱心網友回復:
您以 1 秒的間隔初始化 DispatchTimer:Timer.Interval = new TimeSpan(0,0,1);
并且每個 TimerTick 都會減少您的time欄位。
所以,time應該從你想要倒計時的總秒數開始。如果您從 15 開始,您的倒數計時器將從 15 秒倒計時到零。如果要倒計時 15 分鐘,則必須初始化time為 900 (15 x 60'')。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315365.html
