views:

279

answers:

3

Hi,

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

+2  A: 

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);
Reed Copsey
This, but what he wants to do can easily be done via animation in the UI.
Will
+3  A: 

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.

Steven Robbins
Tks, it worked.FYI, I didn't think about using animation, but it might be a good idea for later on.
David Brunelle
+2  A: 

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;
}
PaulB