while循环中更改的标签不会更新UI

kk6*_*axq 0 c# wpf loops

运行此代码时:

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

}
}
Run Code Online (Sandbox Code Playgroud)

要经常更新标签,窗口永远不会打开.但是,当我删除while循环时,它可以工作,但它只是不更新​​标签...那么如何在没有任何用户输入的情况下更新标签以显示当前时间?谢谢,L

Ree*_*sey 8

问题是你正在阻止你的UI线程.

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

这看起来像:

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;
}
Run Code Online (Sandbox Code Playgroud)

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