制作时钟UWP(C#)

我正在为Windows 10编写应用程序,需要在UI中显示Time。

我做了这样的显示

Time.Text = DateTime.Now.ToString("h:mm:ss tt"); 

但我需要更新它,有关如何做到这一点的任何建议?

在XAML中尝试这个:

   

这是你的代码:

 public sealed partial class ClockPage : Page { DispatcherTimer Timer = new DispatcherTimer(); public ClockPage() { InitializeComponent(); DataContext = this; Timer.Tick += Timer_Tick; Timer.Interval = new TimeSpan(0, 0, 1); Timer.Start(); } private void Timer_Tick(object sender, object e) { Time.Text = DateTime.Now.ToString("h:mm:ss tt"); } } 

显然你需要更改类的名称以匹配你所拥有的,但你明白了。 你可能想通过使用MVVM整理一下,这只是一个简单的例子。

     

 using System; using System.Windows; namespace StkOverflow { public partial class MainWindow { System.Windows.Threading.DispatcherTimer Timer = new System.Windows.Threading.DispatcherTimer(); public DateTime Time { get { return (DateTime)GetValue(TimeProperty); } set { SetValue(TimeProperty, value); } } public static readonly DependencyProperty TimeProperty = DependencyProperty.Register("Time", typeof(DateTime), typeof(MainWindow), new PropertyMetadata(DateTime.Now)); public MainWindow() { InitializeComponent(); this.DataContext = this; Timer.Tick += new EventHandler(Timer_Click); Timer.Interval = new TimeSpan(0, 0, 1); Timer.Start(); } private void Timer_Click(object sender, EventArgs e) { Time = DateTime.Now; } } } 

您只需向您的class级添加一个Timer

 private Timer timer; 

为计时器的Elapsed事件创建一个处理程序:

 private void timer_Elapsed(object sender, ElapsedEventArgs e) { Time.Text = DateTime.Now.ToString("h:mm:ss tt"); } 

然后在窗口的构造函数中,您可以添加:

 timer = new Timer(1000); // let the timer tick every 1000 ms = every second timer.Elapsed += new ElapsedEventHandler(timer_Elapsed); timer.Enabled = true; // Enable it