1

在我的 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();
4

3 回答 3

1

您可以使用计时器。

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

并每秒通知一个属性。

public DateTime Now
{
    get { return DateTime.Now; }
}
于 2013-06-19T17:31:25.793 回答
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;
}
于 2013-06-19T18:00:52.213 回答
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();
        }
于 2013-06-19T17:32:44.717 回答