在WPF的使用者線程中更新UI介面

來源:互聯網
上載者:User
 

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;        }                                                            2007-1-8 Paul.Peng 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.