您可以使用string.Format 格式化。
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
更新:
Xaml:
<StackLayout>
<Label x:Name="lbl_result" FontSize="Large" />
<StackLayout Orientation="Horizontal">
<Button
x:Name="btn_Start"
Clicked="btn_Start_Clicked"
Text="Start" />
<Button
x:Name="btn_Stop"
Clicked="btn_Stop_Clicked"
Text="Stop" />
</StackLayout>
</StackLayout>
后面的代码:
private void btn_Start_Clicked(object sender, EventArgs e)
{
btn_Start.IsVisible = false;
stopWatch.Start();
btn_Stop.IsVisible = true;
}
private void btn_Stop_Clicked(object sender, EventArgs e)
{
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = string.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds/10);
lbl_result.Text = elapsedTime;
btn_Start.IsVisible = true;
btn_Stop.IsVisible = false;
}
更新2:
如果您想实时查看时间,可以使用 Timer。
Xaml:
<StackLayout>
<Label x:Name="lbl_result" FontSize="Large" />
<StackLayout Orientation="Horizontal">
<Button
x:Name="btn_Start"
Clicked="btn_Start_Clicked"
Text="Start" />
<Button
x:Name="btn_Stop"
Clicked="btn_Stop_Clicked"
Text="Stop" />
</StackLayout>
</StackLayout>
后面的代码:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
Timer timer;
int hours = 0, mins = 0, secs = 0, milliseconds = 0;
private void btn_Start_Clicked(object sender, EventArgs e)
{
timer = new Timer();
timer.Interval = 1; // 1 milliseconds
timer.Elapsed += Timer_Elapsed; ;
timer.Start();
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
milliseconds++;
if (milliseconds >= 1000)
{
secs++;
milliseconds = 0;
}
if (secs == 59)
{
mins++;
secs = 0;
}
if (mins == 59)
{
hours++;
mins = 0;
}
Device.BeginInvokeOnMainThread(() =>
{
lbl_result.Text = string.Format("{0:00}:{1:00}:{2:00}.{3:00}", hours, mins, secs, milliseconds / 10);
});
}
private void btn_Stop_Clicked(object sender, EventArgs e)
{
timer.Stop();
timer = null;
}
}
输出: