Updating shortcut contents every second WPF

I try to update the contents of shortcuts every second. Therefore, I define two methods as shown below. I am using startStatusBarTimer() in my Window constructor.

codes:

 private void startStatusBarTimer() { System.Timers.Timer statusTime = new System.Timers.Timer(); statusTime.Interval = 1000; statusTime.Elapsed += new System.Timers.ElapsedEventHandler(statusTimeElapsed); statusTime.Enabled = true; } private void statusTimeElapsed(object sender, ElapsedEventArgs e) { lblNow.Content = DateTime.Now.ToString("yyyy/MM/dd"); } 

But I get this error:

The calling thread cannot access this object because another thread belongs to it.

What's wrong? Or what can I do?

+8
c # wpf xaml
source share
2 answers

You have encountered a problem. Since the past event is called on the background thread , you cannot access the user interface elements from the background thread. You need to put your action on the UI dispatcher so that it UI dispatcher to the UI dispatcher thread -

 private void statusTimeElapsed(object sender, ElapsedEventArgs e) { App.Current.Dispatcher.Invoke((Action)delegate { lblNow.Content = DateTime.Now.ToString("yyyy/MM/dd"); }); } 

OR

You can use DispatcherTimer , which is specially created for this purpose. You can access the user interface controls from the Tick event handler. See Sample here MSDN .

+10
source share

just use the following code to update any control in your WPF application. You must pass this class in the same namespace.

 public static class ExtensionMethods { private static Action EmptyDelegate = delegate() { }; public static void Refresh(this UIElement uiElement) { uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate); } } 

then use as shown below.

 lable1.Refresh(); 
+2
source share

All Articles