在 while 循环中更改的标签不会更新 UI [英] Label changed in while loop does not update UI

查看:36
本文介绍了在 while 循环中更改的标签不会更新 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行此代码时:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        while (true)
        {

            InitializeComponent();

            DateTime dtCurrentTime = DateTime.Now;
            label1.Content = dtCurrentTime.ToLongTimeString();
        }
    }

}
}

为了频繁更新标签,窗口永远不会打开.但是,当我删除 while 循环时,它可以工作,但它只是不更新​​标签......那么我将如何更新标签以显示当前时间而无需任何用户输入?谢谢,L

to update the label frequently, the window never opens. But when I remove the while loop it works but it just doesn't update the label... So how would I update the label to show the current time without any user input? Thanks, L

推荐答案

问题是你阻塞了你的 UI 线程.

The problem is that you're blocking your UI thread.

您不能在 UI 线程上以这种方式循环运行代码.您需要设置一个Timer,并在计时器中更新您的标签,以允许 UI 线程继续执行和处理消息.

You can't run code in a loop this way on the UI thread. You need to setup a Timer, and update your label in the timer, to allow the UI thread to continue executing and process messages.

这看起来像:

public MainWindow()
{
        InitializeComponent();


        DispatcherTimer timer = new DispatcherTimer 
            {
                Interval = TimeSpan.FromSeconds(0.5)
            };
        timer.Tick += (o,e) =>
            {
                DateTime dtCurrentTime = DateTime.Now;
                label1.Content = dtCurrentTime.ToLongTimeString();
            };
        timer.IsEnabled = true;
}

这将导致计时器每秒更新 UI 两次.

This will cause the timer to update the UI two times per second.

这篇关于在 while 循环中更改的标签不会更新 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆