WPF 使用定时器更新UI界面

时间:2025-01-24 10:41:48

不能用Timer了 用DispatchTimer

效果

    <Grid>
        <>
            <RowDefinition Height="227*"/>
            <RowDefinition Height="93*"/>
        </>
        <TextBlock x:Name="Time_Text" HorizontalAlignment="Center" TextWrapping="Wrap" Text="00:00:00" VerticalAlignment="Center" FontSize="72"/>
        <StackPanel HorizontalAlignment="Left" Height="93" ="1" VerticalAlignment="Top" Width="517">
            <Button Content="开始" x:Name="action" Click="action_Click"/>
            <Button Content="停止" x:Name="stop" Click="stop_Click" IsEnabled="False"/>
        </StackPanel>

    </Grid>

     public MainWindow()
        {
            InitializeComponent();
            Time = new DispatcherTimer();
             = (100);
             += Time_Tick;
           
        }

        void Time_Tick(object sender, EventArgs e)
        {
            Time_Text.Text = ("HH:mm:ss");
        }
        private  DispatcherTimer Time=null;
        private void action_Click(object sender, RoutedEventArgs e)
        {
            if (Time != null) 
            {
                ();
                 = false;
                 = true;
            }
        }

        private void stop_Click(object sender, RoutedEventArgs e)
        {
            if (Time != null)
            {
                ();
                 = true;
                 = false;
            }
        }