How to use a timer to display content?
I am having issues with getting my timer to change content on a window.
I initialize my timer by:
timeOutTimer = new System.Timers.Timer(15000);
timeOutTimer.Ela开发者_如何学Pythonpsed += new ElapsedEventHandler(timeOutEvent);
timeOutTimer.Enabled = true;
timeOutTimer.AutoReset = false;
timeOutTimer.Start();
I have a ContentControl which is Hidden.
When the timer passes 15 seconds it should change the visibility of the ContentControl
private void timeOutEvent(object sender, ElapsedEventArgs e)
{
TicketContent.Visibility = Visibility.Visible;
Console.WriteLine("TIMED OUT");
timeOutTimer.Stop();
}
I am getting an exception : System.InvalidOperationException
What am I doing wrong?
Thanks in advance!
Why not use DispatcherTimer
timer = new DispatcherTimer(
TimeSpan.FromSeconds(15),
DispatcherPriority.Background,
TimeoutEvent,
this.Dispatcher);
timer.Start();
When you start a timer, it begins on a separate non UI thread. As it is in a separate thread it cannot access elements in the UI thread. A delegate in combination with a Dispatcher.BeginInvoke() method will allow you to modify the properties of UI elements.
private void timeOutEvent(object sender, ElapsedEventArgs e)
{
TicketContent.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new InvokeDelegate(TimeOutEvent));
Console.WriteLine("TIMED OUT");
timeOutTimer.Stop();
}
public delegate void InvokeDelegate();
private void TimeOutEvent()
{
TicketContent.Visibility = Visibility.Visible;
}
精彩评论