如何将DateTime.Now绑定到TextBlock?

时间:2013-06-19 17:19:43

标签: c# windows-8 windows-runtime

在我的Windows 8应用程序中,我想在TextBlock元素中显示当前时间。时间值应该每秒更新一次。以下代码工作正常,但我认为这不是理想的解决方案。那么有更好的方法吗?

public class Clock : Common.BindableBase {
    private string _time;
    public string Time {
        get { return _time; }
        set { SetProperty<string>(ref _time, value); }
    }
}

private void startPeriodicTimer() {
    if (PeriodicTimer == null) {
        TimeSpan period = TimeSpan.FromSeconds(1);

        PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) => {

            Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () => {
                    DateTime time = DateTime.Now;
                    clock.Time = string.Format("{0:HH:mm:ss tt}", time);
                    [...]
                });

        }, period);
    }
}

在LoadState方法中:

clock = new Clock();
clock.Time = string.Format("{0:HH:mm:ss tt}", DateTime.Now);
currentTime.DataContext = clock;
startPeriodicTimer();

3 个答案:

答案 0 :(得分:1)

您可以使用计时器。

var timer = new Timer { Interval = 1000 };
timer.Elapsed += (sender, args) => NotifyPropertyChanged("Now");
timer.Start();

每秒通知一个房产。

public DateTime Now
{
    get { return DateTime.Now; }
}

答案 1 :(得分:0)

我是如何使用Timer

在我的应用程序中完成的
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            TxtHour.Text = DateTime.Now.ToString("HH:mm:ss");
        }
private void MainWindow_OnLoad(object sender, RoutedEventArgs e)
        {
            System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
            dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
            dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
            dispatcherTimer.Start();
            TxtDate.Text = DateTime.Now.Date.ToShortDateString();
        }

答案 2 :(得分:0)

WinRT有DispatcherTimer级。你可以使用它。

XAML

<Page.Resources>
    <local:Ticker x:Key="ticker" />
</Page.Resources>

<TextBlock Text="{Binding Source={StaticResource ticker}, Path=Now}" FontSize="20"/>

C#

public class Ticker : INotifyPropertyChanged
{
    public Ticker()
    {
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += timer_Tick;
        timer.Start();
    }

    void timer_Tick(object sender, object e)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs("Now"));
    }

    public string Now
    {
        get { return string.Format("{0:HH:mm:ss tt}", DateTime.Now); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}