I have a WPF app with a textblock that displays the current time. Said textblock is bound to a DependencyProperty on the ViewModel. Naturally I need to keep updating the time, so I used a timer (System.Threading.Timer) like so:
public MainViewModel()
{
_dateTimer = new Timer(_dateTimer_Tick, null, 0, 60000);
}
void _dateTimer_Tick(object sender)
{
Time = DateTime.Now.ToString("HH:mm");
Date = DateTime.Now.ToString("D");
}
The thing is, when the callback is called, the app exits... bummer (output says: "A first chance exception of type 'System.InvalidOperationException' occurred in WindowsBase.dll" just when it's about to write to the Time DP).
If I use a DispatcherTimer everything works fine. I don't mind using a DispatcherTimer, it's just that the app is quite big and I wanted to tweak out its performance the best I could. As far as I can see I'm not accessing the UI thread (I'm just updating a property) so a DispatcherTimer wouldn't be needed.
Am I missing something?
Thanks.
EDIT: The properties are defined like this:
public string Time
{
get { return (string)GetValue(TimeProperty); }
set { SetValue(TimeProperty, value); }
}
// Using a DependencyProperty as the backing store for Time. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TimeProperty =
DependencyProperty.Register("Time", typeof(string), typeof(MainViewModel), new UIPropertyMetadata(""));
(Date is the same)