WPF中UI线程更新
2011-11-11 16:11
WPF
中
UI
线程队列由
Dispatcher
来管理和调度,所以当用户线程中更新
UI
时,必须通过
Dispatche
来调度,下面这个小例子将给用户展示如何在用户线程中更新当前的时间
.
前台的
XAML
代码如下:
<
Window
x:Class
=
"ThreadInvoke.Window1"
xmlns
=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
=
"http://schemas.microsoft.com/winfx/2006/xaml"
Title
=
"ThreadInvoke"Height="300"Width="300"
>
<
StackPanel
Orientation
=
"Vertical">
<
StackPanel
Orientation
=
"Horizontal">
<
Button
Content
=
"Ok"Click="okClick"Width="50"/>
<
Button
Content
=
"Stop"Click="stopClick"Width="50"/>
</
StackPanel
>
<
TextBox
Name
=
"timeText"></TextBox>
</
StackPanel
>
</
Window
>
后台的主要代码如下:
//
申明一个代理用于想
UI
更新时间
private
delegatevoidDelegateSetCurrentTime();
//
申明一个变量,用于停止时间的跳动
private
bool stopFlag = false;
//
处理开始和结束事件
private
void okClick(object sender,RoutedEventArgs args)
{
stopFlag = false;
Thread thread = newThread(newThreadStart(refreshTime));
thread.Start();
}
privatevoid stopClick(object sender, RoutedEventArgs args)
{
stopFlag = true;
}
//用户线程的实现函数
privatevoid refreshTime()
{
while (!stopFlag)
{
//向UI界面更新时钟显示 Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.SystemIdle, newDelegateSetCurrentTime(setCurrentTime));
}
}
privatevoid setCurrentTime()
{
String currentTime = System.DateTime.Now.ToString();
timeText.Text = currentTime;
}
2007-1-8
Paul.Peng