近段時間在自學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} \r\n",sMsg)); }); }
