秒表总是输出 00:00:00:00

Stopwatch always outputs 00:00:00:00

在我的 WPF 程序中有一个带有此代码隐藏的按钮:

**Outside the Click event:**
bool started = false;

**In the Click Event:**
if (started == false)
{
    started = true;

    btnStart.Content = "Stop";

    //---------Clock Code-------------
    stopwatch.Start();
}
else
{
    started = false;
    btnStart.Content = "Start";

    //---------Clock Code------------

    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);
    tbDuration.Text = elapsedTime;
}

但是如果我启动程序并按下按钮,它总是显示 0。 我无法调试它,因为 Visual Studio 崩溃了...

我做错了什么?

或者你有更好的方法吗? 我只是想测量两次按下之间的时间并将其输出到文本框中。

我还希望在文本框中实时监控时间。

谢谢

假设您的代码看起来像这样它工作正常:

    public Stopwatch stopwatch = new Stopwatch();
    bool started = false;

    private void button1_Click(object sender, EventArgs e)
    {

        if (started == false)
        {
            started = true;

            button1.Text = "Stop";

            //---------Clock Code-------------

            stopwatch.Start();




        }
        else
        {
            started = false;
            button1.Text = "Start";

            //---------Clock Code------------

            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);

            MessageBox.Show(elapsedTime);
        }
    }

解决方案:(来自@TheGeneral) 将秒表放入实例成员中:

private Stopwatch stopwatch = new Stopwatch();