| 发表于:2007-03-27 20:00:4611楼 得分:0 |
参考: 在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; } | | |
|