开发者

C# WPF timer (stopwatch) with DispatcherTimer

I'm trying to make a simple stopwatch but it just doesn't work.. The app just crashes when I press the buttons. What's wrong?

public partial class MainWindow : Window
{
    private DispatcherTimer timer;

    public MainWindow()
    {
        InitializeComponent();
        DispatcherTimer timer = new DispatcherTimer(new TimeSpan(0, 0, 0, 0, 1), DispatcherPriority.Normal, delegate
        {
            this.Show.Text = DateTime.Now.ToString("HH:开发者_JAVA百科mm:ss:fff");
        }, this.Dispatcher);
    }

    private void Start(object sender, RoutedEventArgs e)
    {
        timer.Start();
    }

    private void Stop(object sender, RoutedEventArgs e)
    {
            timer.Stop();
    }
}


Your problem is this:

DispatcherTimer timer = ...

you have created a new instance of the timer which is scoped to your constructor. You have not set the member variable timer. This means when you hit the start button you will be trying to start a timer that has not been instantiated yet and you will get a NullReferenceException. I suggest you:

  • rename the member variable timer to _timer. This helps avoid confusion to similarly named local variables.
  • change the line DispatcherTimer timer = new DispatcherTimer to _timer = new DispatcherTimer(...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜