我正在为Windows 10编写应用程序,需要在UI中显示Time.
我做了这样的显示
Time.Text = DateTime.Now.ToString("h:mm:ss tt");
Run Code Online (Sandbox Code Playgroud)
但我需要更新它,有关如何做到这一点的任何建议吗?
小智 8
在XAML中尝试这个:
<TextBlock x:Name="Time" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
Run Code Online (Sandbox Code Playgroud)
这是你的代码:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
显然你需要更改类的名称以匹配你所拥有的,但你明白了.你可能想通过使用MVVM整理一下,这只是一个简单的例子.
小智 7
<Window x:Class="StkOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:StkOverflow"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Text="{Binding Time, StringFormat='{}{0: h:mm:ss tt}'}"></TextBlock>
</Grid>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)