如何在 Xamarin 中单击按钮停止秒表?

how to stop a stopwatch with a button click in Xamarin?

目标是测量用户的反应时间。单击开始按钮后 3-10 秒,它应该启动秒表并使停止按钮可见。用户单击停止按钮后,它应该停止手表并显示用户响应所用的毫秒数。

关于如何实现一个循环来检查按钮是否已被按下并停止手表而不阻止用户单击按钮的解决方案,我遇到了麻烦。

public partial class Main : ContentPage
{

    public Main()
    {
        InitializeComponent();
    }
    public void OnStartClicked(object sender,EventArgs args)
    {
        Stopwatch stopWatch = new Stopwatch();
        startButton.IsVisible = false;
        BG.BackgroundColor = Color.Red;
        status_text.Text = "Get Ready";
        Random R = new Random();

         Device.StartTimer(TimeSpan.FromSeconds(R.Next(3, 10)), () =>
         {

             stopWatch.Start();
             stopButton.IsVisible = true;
             BG.BackgroundColor = Color.Green;


             long elapsed = stopWatch.ElapsedMilliseconds;
             stopWatch.Stop();
             status_text.Text = elapsed.ToString();
             return false;
         });
    }

}}

将秒表用作 成员变量 并在 OnStopClicked-Event 中停止手表。停止后读取经过的时间。除了 button.IsVisible 你还可以使用 button.IsEnabled.

public partial class MainPage : ContentPage
{
    Stopwatch mStopWatch = new Stopwatch();

    public MainPage()
    {
        InitializeComponent();
    }

    private void StartButton_Clicked(object sender, EventArgs e)
    {                       
        startButton.IsVisible = false;
        BG.BackgroundColor = Color.Red;
        status_text.Text = "Get Ready";
        Random R = new Random();

        Device.StartTimer(TimeSpan.FromSeconds(R.Next(3, 10)), () =>
        {
            mStopWatch.Start();
            stopButton.IsVisible = true;
            BG.BackgroundColor = Color.Green;                
            return false;
        });
    }

    private void StopButton_Clicked(object sender, EventArgs e)
    {
        mStopWatch.Stop();
        long elapsed = mStopWatch.ElapsedMilliseconds;            
        status_text.Text = elapsed.ToString();
        mStopWatch.Reset();
        stopButton.IsVisible = false;
        startButton.IsVisible = true;
    }
}