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元素,不会引发跨线程调用的异常.

构造函数:

DispatcherTimer( ),

DispatcherTimer(DispatcherPriority),

DispatcherTimer(DispatcherPriority,Dispatcher),

 DispatcherTimer(TimeSpan, DispatcherPriority,Event Handler,Dispatcher)

属性:Interval, IsEnable, Tag, Dispatcher

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

事件:Tick

测试代码:

创建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();         }

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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容