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: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:
timer
to _timer
. This helps avoid confusion to similarly named local variables.DispatcherTimer timer = new DispatcherTimer
to _timer = new DispatcherTimer(...