#370 – 通过绑定显示当前时间(Binding a Label’s Content to the Current Date and Time)

你可以通过绑定Label控件的Content属性到DateTime.Now属性显示当前的日期和时间,但是如果仅仅是直接绑定,时间是不会自动更新的。

需要显示时间持续更新,你需要绑定一个可以持续通过INotifyPropertyChanged 接口通知改变的属性。这个我们可以通过一个计时器来实现。

XAML代码:

 <Label Content="{Binding CurrentDateAndTime}" ContentStringFormat="Current time - {0:T}"/>

在C#代码中,我们定义一个属性表示显示的时间,并且开启计时器Timer:

	public DateTime CurrentDateAndTime { get; set; }

        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;

            DispatcherTimer dayTimer = new DispatcherTimer();
            dayTimer.Interval = TimeSpan.FromMilliseconds(500);
            dayTimer.Tick += new EventHandler(dayTimer_Tick);
            dayTimer.Start();
        }

每当计时器触发,我们就更新定义的属性的值并发送INotifyPropertyChanged.PropertyChanged 事件。

 	void dayTimer_Tick(object sender, EventArgs e)
        {
            CurrentDateAndTime = DateTime.Now;

            PropertyChanged(this, new PropertyChangedEventArgs("CurrentDateAndTime"));
        }

结果如下:



原文地址:https://wpf.2000things.com/2011/08/23/370-binding-a-labels-content-to-the-current-date-and-time-part-ii/


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值