wpf中使用线程的问题
2013-12-24 18:11
330 查看
http://social.msdn.microsoft.com/Forums/zh-CN/504fa86b-7d2d-4424-8f6f-ac9b3a9d480e/wpf
xaml:
后台:
这应该符合你的情况了,后台线程中要获得控件属性,并修改控件属性。建议用MVVM模式,把控件属性绑定到类,代码会更“干净”。
xaml:
<StackPanel Orientation="Vertical"> <TextBox Name="textBox1" Text="20"/> <TextBlock Name="textBlock1"/> <Button Content="Button" Click="button1_Click" /> </StackPanel>
后台:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { using (BackgroundWorker bw = new BackgroundWorker()) { bw.DoWork += new DoWorkEventHandler(bw_DoWork); bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); bw.RunWorkerAsync(); } } void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { textBlock1.Text = "completed"; } void bw_DoWork(object sender, DoWorkEventArgs e) { int times = 0; Dispatcher.Invoke(new Action(delegate() { times = Convert.ToInt32(textBox1.Text); })); for (int i = 0; i < times; i++) { Dispatcher.BeginInvoke(new Action(delegate() { textBlock1.Text = string.Format("current i:{0}", i); })); Thread.Sleep(new TimeSpan(0, 0, 1)); } } }
这应该符合你的情况了,后台线程中要获得控件属性,并修改控件属性。建议用MVVM模式,把控件属性绑定到类,代码会更“干净”。
相关文章推荐
- CSocket跨线程使用问题和其他
- QT在子线程中使用QAxWidget需要初始化COM的问题
- 在分线程使用MBProgressHUD崩溃问题
- android 线程中的ui问题 Handler的基本使用 关于获取动态时间在ui的问题
- WPF的DataGrid的使用技巧—列宽调整和列排序问题
- 关于在线程中使用AfxGetMainWnd()出错的问题,终于找到了
- 多线程使用notify和wait进行线程间通信丢失信号的问题
- C# 子线程使用主线程中的控件问题
- Java实现多线程经典问题:使用三个线程实现输出ABCABC循环
- 线程中使用STL queue的问题
- ASP.NET Boilerplate 学习 AspNet Core2 浏览器缓存使用 c#基础,单线程,跨线程访问和线程带参数 wpf 禁用启用webbroswer右键菜单 EF Core 2.0使用MsSql/MySql实现DB First和Code First ASP.NET Core部署到Windows IIS QRCode.js:使用 JavaScript 生成
- WPF调用线程 解决“调用线程无法访问此对象,因为另一个线程拥有该对象“问题
- WPF项目中使用水晶报表for vs2010时的一个找不到程序集的问题
- 使用线程新建WPF窗体(公用进度条窗体)
- 使用sem_t导致不能用gdb调试及线程非正常终止后message queue异常的问题
- Unity关于有些代码不能在除主线程外的线程使用的问题
- iphone线程中使用异步网络的问题,以及如何用NSRunLoop来解决
- .NET中静态变量的使用需要注意线程安全问题
- Android高手进阶教程(十九)之---Android开发中,使用线程应该注意的问题!
- 关于海思HI3531A平台使用std::thread创建线程问题(未解决)