Reputation: 6440
I have an application where I need to switch visibility of some controls using a timer. Each 5 seconds, some controls disappears while some other appears. When I used a timer, it says that cannot change the visibility because the timer thread is not the owner of the control.
How can we bypass that?
Tks
Upvotes: 0
Views: 2386
Reputation: 24382
Just use the DispatcherTimer. The code called on each tick is automatically run on the UI thread.
eg. (from MSDN)
// DispatcherTimer setup
var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,5);
dispatcherTimer.Start();
// System.Windows.Threading.DispatcherTimer.Tick handler
//
// Updates the current seconds display
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
// Updating the Label which displays the current second
lblSeconds.Content = DateTime.Now.Second;
}
Upvotes: 6
Reputation: 26599
Either use the Dispatcher to marshall it back to the UI thread, or you might want to consider using an animation instead? It would be very straightforward to setup an timeline in Blend to do this entirely in XAML.
Upvotes: 3
Reputation: 564413
You can use SynchronizationContext.Post
or Dispatcher.Invoke
to marshall the UIElement.Visible property set back onto the UI thread.
This can be as simple as something like:
App.SynchronizationContext.Post(new SendOrPostCallback((state) =>
{
theControl.Visible = Visibilty.Visible;
}), null);
Upvotes: 2