C# WPF 使用委托修改UI控件

近段时间在自学WPF,是一个完全不懂WPF的菜鸟,对于在线程中修改UI控件使用委托做一个记录,给自已以后查询也给需要的参考:

C# 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="" Width="" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Grid>
<ScrollViewer>
<RichTextBox HorizontalAlignment="Stretch" Margin="" Name="richTextBox1" VerticalAlignment="Stretch" />
</ScrollViewer>
</Grid>
</Window>

二 在界面启动时开启两个线程:

         private void Window_Loaded(object sender, RoutedEventArgs e)
{
//创建线程1
Thread t1 = new Thread(new ThreadStart(T1));
t1.Start(); //创建线程2
Thread t2 = new Thread(new ThreadStart(T2));
t2.Start();
}

三 线程调用函数:

        /// <summary>
/// 线程1调用函数
/// add by
/// </summary>
private void T1()
{
while (true)
{
Thread.Sleep(TimeSpan.FromSeconds());
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());
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));
});
}
上一篇:c++学习之初话 函数指针和函数对象 的因缘


下一篇:java_annotation_02