每秒刷新一次标签内容 WPF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18816523/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Refreshing Label content every second WPF
提问by Babak.Abad
I'm trying to refresh a label content every second. So I define two methods as below. I use startStatusBarTimer()in my constructor of Window.
我正在尝试每秒刷新一次标签内容。所以我定义了两种方法如下。我startStatusBarTimer()在我的构造函数中使用Window.
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 a different thread owns it.
调用线程无法访问此对象,因为其他线程拥有它。
What is wrong? Or What can I do?
怎么了?或者我能做什么?
回答by Rohit Vats
You are facing thread affinityissue. Since elapsed event is called on background thread, you cannot access UI controls from background thread. You need to put your action on UI dispatcherso that it gets dispatch to UI thread -
您正面临线程关联问题。由于 elapsed 事件被调用background thread,您无法从后台线程访问 UI 控件。您需要执行操作,UI dispatcher以便将其分派到 UI 线程 -
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 DispatcherTimerwhich is built specially for this purpose. You can access UI controls from its Tickevent handler. Refer to the sample here at MSDN.
您可以使用DispatcherTimer专门为此目的构建的。您可以从其Tick事件处理程序访问 UI 控件。请参阅MSDN此处的示例。
回答by Jeetendra Negi
just use following code for refreshing any control in WPF application.you must past this class in your same namespace.
只需使用以下代码刷新 WPF 应用程序中的任何控件。您必须在同一命名空间中传递此类。
public static class ExtensionMethods
{
private static Action EmptyDelegate = delegate() { };
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
}
}
after that use like following.
之后使用如下。
lable1.Refresh();

