TextBlock WPF中的时间 [英] Time in TextBlock WPF

查看:229
本文介绍了TextBlock WPF中的时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

再次问好.

我开始使用WPF,但现在遇到了问题.

我需要用实际时间做一个TextBlock.我尝试在代码中指定:

Hello again.

I''m starting to use WPF and now I have a problem.

I need to do a TextBlock with the actual time. I tried specifying in the code:

Textblock1.Text=DateTime.Now.ToShortTimeString();



但是执行表单时出现此错误:

The calling thread cannot access this object because a different thread owns it.

如何显示现在时间?

感谢



But when execute the form appears this error:

The calling thread cannot access this object because a different thread owns it.

How I can show the now time?

Thanks

推荐答案

查看此内容以了解WPF线程模型以及如何从UI线程以外的其他线程访问UI元素...

线程模型 [
See this to learn about the WPF threading model and accessing UI elements from threads other than the UI thread...

Threading Model[^]


尝试使用Dispatcher ,如

了解Abhinav和Mark正确答案的更多详细信息:

您无法从非UI线程调用与UI相关的任何操作.相反,您需要使用System.Windows.Threading.DispatcherInvokeBeginInvoke方法(对于Forms或WPF)或System.Windows.Forms.Control(仅对于Forms).

在我过去的答案中,您将找到有关其工作原理的详细说明和代码示例:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview Scanner和MD5的问题 [如何获取keydown事件在vb.net中的不同线程上操作 [启用禁用+多线程后控件事件不会触发 [ ^ ].

—SA
More details to understand correct answer by Abhinav and Mark:

You cannot call anything related to UI from non-UI thread. Instead, you need to use the method Invoke or BeginInvoke of System.Windows.Threading.Dispatcher (for both Forms or WPF) or System.Windows.Forms.Control (Forms only).

You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].

See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].

—SA


这篇关于TextBlock WPF中的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆