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

时间:2017-03-26 16:17:20

标签: xamarin timer xamarin.forms stopwatch

目标是衡量用户的反应时间。单击开始按钮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;
         });
    }

}}

1 个答案:

答案 0 :(得分:1)

将StopWatch用作成员变量,并在 OnStopClicked-Event 中停止观看。读取停止后经过的时间。而不是button.IsVisible你也可以使用按钮。 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;
    }
}