WPF DispatcherTimer 更新UI

詳細信息參考MSDN:DispatcherTimer Class (System.Windows.Threading) | Microsoft Docs

Namespace:

System.Windows.Threading

Assembly: WindowsBase.dll

A timer that is integrated into the?Dispatcher?queue which is processed at a specified interval of time and at a specified priority.

運行在UI線程上的定時器,可以直接更新UI元素,不會引發(fā)跨線程調用的異常.

構造函數(shù):

DispatcherTimer( ),

DispatcherTimer(DispatcherPriority),

DispatcherTimer(DispatcherPriority,Dispatcher),

?DispatcherTimer(TimeSpan, DispatcherPriority,Event Handler,Dispatcher)

屬性:Interval, IsEnable, Tag, Dispatcher

主要方法:Start( ),Stop( )

事件:Tick

測試代碼:

創(chuàng)建2個DispatchTimer對象更新UI,顯示當前時間

前臺代碼:

? ? <Grid>

? ? ? ? <Grid.RowDefinitions>
? ? ? ? ? ? <RowDefinition Height="Auto"/>
? ? ? ? ? ? <RowDefinition Height="Auto"/>
? ? ? ? ? ? <RowDefinition Height="Auto"/>
? ? ? ? </Grid.RowDefinitions> ? ? ? ? <Label Grid.Row="0 " Margin="5" FontWeight="ExtraBlack" ?x:Name="lblMsg">Test</Label>

? ? ? ? <TextBlock Grid.Row="1" Margin="5" FontWeight="ExtraBlack" HorizontalAlignment="Center" x:Name="txtMsg">Test Text</TextBlock>

? ? </Grid>

?后臺代碼:

? ? ? ? DispatcherTimer t1; ? ? ? ? DispatcherTimer t2;


? ? ? ? private void Window_Loaded(object sender, RoutedEventArgs e)
? ? ? ? {
? ? ? ? ? ? t1 = new DispatcherTimer();
? ? ? ? ? ? t1.Tick += T1_Tick;
? ? ? ? ? ? t1.Interval = new TimeSpan(0, 0, 1); ? ? ? ? ? ? t1.Start();


? ? ? ? ? ? t2 = new DispatcherTimer();
? ? ? ? ? ? t2.Tick += T2_Tick;
? ? ? ? ? ? t2.Interval = TimeSpan.FromSeconds(1); ? ? ? ? ? ? t2.Start();

? ? ? ? }

? ? ? ? private void T2_Tick(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? txtMsg.Text = DateTime.Now.ToString("G");
? ? ? ? ? ? // DateTime.Now.ToString("HH:mm:ss.fff"); ? ? ? ? }

? ? ? ? private void T1_Tick(object sender, EventArgs e)
? ? ? ? {
? ? ? ? ? ? lblMsg.Content = DateTime.Now.Second;
? ? ? ? ? ? CommandManager.InvalidateRequerySuggested(); ? ? ? ? }

本文使用 文章同步助手 同步

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容