近段时间在自学WPF,是一个完全不懂WPF的菜鸟,对于在线程中修改UI控件使用委托做一个记录,给自已以后查询也给需要的参考:
界面只放一个RichTextBox,在窗体启动时开起两个线程,调用两个函数,每隔1秒写一次当前时间
一 界面XAML如下:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded"> <Grid> <ScrollViewer> <RichTextBox HorizontalAlignment="Stretch" Margin="12" Name="richTextBox1" VerticalAlignment="Stretch" /> </ScrollViewer> </Grid> </Window>
二 在界面启动时开启两个线程:
1 private void Window_Loaded(object sender, RoutedEventArgs e) 2 { 3 //创建线程1 4 Thread t1 = new Thread(new ThreadStart(T1)); 5 t1.Start(); 6 7 //创建线程2 8 Thread t2 = new Thread(new ThreadStart(T2)); 9 t2.Start(); 10 }
三 线程调用函数:
/// <summary> /// 线程1调用函数 /// add by /// </summary> private void T1() { while (true) { Thread.Sleep(TimeSpan.FromSeconds(1)); ShowMsg(string.Format("T1 {0}", System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:fff"))); } } /// <summary> /// 线程2调用函数 /// add by /// </summary> private void T2() { while (true) { Thread.Sleep(TimeSpan.FromSeconds(1)); ShowMsg(string.Format("T2 {0}", System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss:fff"))); } }
三 写前端函数:
private void ShowMsg(string sMsg) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate() { richTextBox1.AppendText(string.Format("{0} ",sMsg)); }); }