您的位置:首页 > 产品设计 > UI/UE

在wpf的用户线程中更新ui界面

2010-12-08 14:55 435 查看

在wpf的用户线程中更新ui界面

作者: maco 和线程相关 20071124

简介:这是在wpf的用户线程中更新ui界面的详细页面,介绍了和线程,有关的知识,要查看更多相关信息,请点击此处
wpf中ui线程队列由dispatcher来管理和调度,所以当用户线程中更新ui时,必须通过dispatche来调度,下面这个小例子将给用户展示如何在用户线程中更新当前的时间.

前台的xaml代码如下:
<windowx: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"
>
<stackpanelorientation="vertical">
<stackpanelorientation="horizontal">
<buttoncontent="ok"click="okclick"width="50"/>
<buttoncontent="stop"click="stopclick"width="50"/>
</stackpanel>
<textboxname="timetext"></textbox>
</stackpanel>
</window>

后台的主要代码如下:

//申明一个代理用于想ui更新时间
private delegate void delegatesetcurrenttime();

//申明一个变量,用于停止时间的跳动
private bool stopflag = false;

//处理开始和结束事件
private void okclick(object sender,routedeventargs args)
{
stopflag = false;
thread thread = new thread(new threadstart(refreshtime));
thread.start();
}

private void stopclick(object sender, routedeventargs args)
{
stopflag = true;
}

//用户线程的实现函数
private void refreshtime()
{
while (!stopflag)
{
//向ui界面更新时钟显示 dispatcher.invoke(system.windows.threading.dispatcherpriority.systemidle, new delegatesetcurrenttime(setcurrenttime));
}
}

private void setcurrenttime()
{
string currenttime = system.datetime.now.tostring();
timetext.text = currenttime;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: