WPF用户线程使用技巧分享

WPF开发工具是一款功能强大的图形界面显示工具。在开发人员眼中,它的作用是非常强大的。WPF中UI线程队列由Dispatcher来管理和调度,所以当WPF用户线程中更新UI时,必须通过Dispatche来调度,下面这个小例子将给用户展示如何在用户线程中更新当前的时间。#t#

前台的XAML代码如下:

  1. < Windowx:ClassWindowx:Class=
    "ThreadInvoke.Window1" 
  2. xmlns="http://schemas.microsoft
    .com/winfx/2006/xaml/presentation"
     
  3. xmlns:x="http://schemas.microsoft
    .com/winfx/2006/xaml"
     
  4. Title="ThreadInvoke"Height="300"
    Width="300" 
  5. > 
  6. < StackPanelOrientation
    StackPanelOrientation="Vertical"> 
  7. < StackPanelOrientationStackPanel
    Orientation
    ="Horizontal"> 
  8. < ButtonContentButtonContent="Ok"
    Click="okClick"Width="50"/> 
  9. < ButtonContentButtonContent="Stop"
    Click="stopClick"Width="50"/> 
  10. < /StackPanel> 
  11. < TextBoxNameTextBoxName="timeText">
    <
     /TextBox> 
  12. < /StackPanel> 
  13. < /Window> 

WPF用户线程后台的主要代码如下:

 
 
 
  1. //申明一个代理用于想UI更新时间  
  2. private delegate void 
    DelegateSetCurrentTime();  
  3. //申明一个变量,用于停止时间的跳动  
  4. private bool stopFlag = false;  
  5. //处理开始和结束事件  
  6. private void okClick(object 
    sender,RoutedEventArgs args)  
  7. {  
  8. stopFlag = false;  
  9. Thread thread = new Thread(new 
    ThreadStart(refreshTime));  
  10. thread.Start();  
  11. }  
  12. private void stopClick(object 
    sender, RoutedEventArgs args)  
  13. {  
  14. stopFlag = true;  
  15. }  
  16. //用户线程的实现函数  
  17. private void refreshTime()  
  18. {  
  19. while (!stopFlag)  
  20. {  
  21. //向UI界面更新时钟显示 Dispatcher.
    Invoke(System.Windows.Threading.
    DispatcherPriority.SystemIdle, 
    new DelegateSetCurrentTime
    (setCurrentTime));  
  22. }  
  23. }  
  24. private void setCurrentTime()  
  25. {  
  26. String currentTime = System.
    DateTime.Now.ToString();  
  27. timeText.Text = currentTime;  

以上就是对WPF用户线程的一些相关知识的介绍。

THE END