I am using a Dispatch timer set to fire every 20 seconds in which I need to update a databound textblock via it’s propery in my view model. This is the timer code in the viewmodel:
public TestViewModel()
{
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Interval = new TimeSpan(0, 0, 20);
_dispatcherTimer.Tick += new EventHandler(_dispatcherTimer_Tick);
_dispatcherTimer.Start();
}
void _dispatcherTimer_Tick(object sender, EventArgs e)
{
if(blah == blah)
{
_dispatcher.BeginInvoke(() =>
{
// DoneEnabled is a boolean property that my
// textblock's IsEnabled property is bound to
DoneEnabled = true;
});
}
}
private bool _doneEnabled;
/// <summary>
/// Gets or sets a value indicating whether [done enabled].
/// </summary>
/// <value>
/// <c>true</c> if [done enabled]; otherwise, <c>false</c>.
/// </value>
public bool DoneEnabled
{
get { return _doneEnabled; }
set
{
_doneEnabled = value;
RaisePropertyChanged("DoneEnabled");
}
}
The button gets enabled everywhere else when I try and do so in my viewmodel by updating this property EXCEPT in the timer’s event handler. Any idea if I’m missing something here?
Thanks.
UPDATE:
Edited the _dispatcherTimer_Tick method to the following
void _dispatcherTimer_Tick(object sender, EventArgs e)
{
if(blah == blah)
{
// DoneEnabled is a boolean property that my
// textblock's IsEnabled property is bound to
DoneEnabled = true;
}
}
Works like a charm!
Since you are using a
DispatchTimerthe method_dispatcherTimer_Tickalready runs on the UI/Dispatcher thread (this is built in for convenience of use) – just do:From MSDN: