运行此代码时:
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
问题是你阻塞了你的 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;
}
这将导致计时器每秒更新 UI 两次。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)