WPF用戶線程使用技巧分享
作者:佚名
WPF用戶線程中更新UI,需要通過Dispatche來進(jìn)行調(diào)度。我們將會在這篇文章中為大家詳細(xì)介紹一下有關(guān)這一方法的相關(guān)應(yīng)用。
WPF開發(fā)工具是一款功能強大的圖形界面顯示工具。在開發(fā)人員眼中,它的作用是非常強大的。WPF中UI線程隊列由Dispatcher來管理和調(diào)度,所以當(dāng)WPF用戶線程中更新UI時,必須通過Dispatche來調(diào)度,下面這個小例子將給用戶展示如何在用戶線程中更新當(dāng)前的時間。#t#
前臺的XAML代碼如下:
- < Windowx:ClassWindowx: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
StackPanelOrientation="Vertical"> - < StackPanelOrientationStackPanel
Orientation="Horizontal"> - < ButtonContentButtonContent="Ok"
Click="okClick"Width="50"/> - < ButtonContentButtonContent="Stop"
Click="stopClick"Width="50"/> - < /StackPanel>
- < TextBoxNameTextBoxName="timeText">
< /TextBox> - < /StackPanel>
- < /Window>
WPF用戶線程后臺的主要代碼如下:
- //申明一個代理用于想UI更新時間
- private delegate void
DelegateSetCurrentTime();- //申明一個變量,用于停止時間的跳動
- private bool stopFlag = false;
- //處理開始和結(jié)束事件
- 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;
- }
- //用戶線程的實現(xiàn)函數(shù)
- 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;
- }
以上就是對WPF用戶線程的一些相關(guān)知識的介紹。
責(zé)任編輯:曹凱
來源:
CSDN