制作时钟UWP(C#)

时间:2016-07-25 08:15:57

标签: c# xaml uwp

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

我做了这样的显示

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

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

3 个答案:

答案 0 :(得分: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>

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

答案 1 :(得分:7)

在XAML中尝试:

    <TextBlock x:Name="Time" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>

这是你的代码:

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整理一下,这只是一个简单的例子。

答案 2 :(得分:2)

您只需向班级添加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