wpf - 绑定(bind)到 DateTime.Now。更新值

标签 wpf binding

嗯,我需要将 DateTime.Now 绑定(bind)到 TextBlock,我使用了它:

 Text="{Binding Source={x:Static System:DateTime.Now},StringFormat='HH:mm:ss tt'}"

现在,如何强制它更新?这是加载控件的时间,并且不会更新它...

最佳答案

这是a link使用 INotifyPropertyChanged 的​​“Ticker”类,因此它会自动更新。这是该网站的代码:

namespace TheJoyOfCode.WpfExample
{
    public class Ticker : INotifyPropertyChanged
    {
        public Ticker()
        {
            Timer timer = new Timer();
            timer.Interval = 1000; // 1 second updates
            timer.Elapsed += timer_Elapsed;
            timer.Start();
        }

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

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

        public event PropertyChangedEventHandler PropertyChanged;
    }
}


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

<TextBox Text="{Binding Source={StaticResource ticker}, Path=Now, Mode=OneWay}"/>
<小时/>

声明:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

现在这可以工作了:

<TextBox Text="{Binding Source={StaticResource ticker}, Path=Now, Mode=OneWay}"/>

关于wpf - 绑定(bind)到 DateTime.Now。更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3354793/

相关文章:

wpf - 关于WPF MVVM和用户控件的菜鸟问题

wpf - DatePicker System.FormatException

c# - 使用 .Substring 逐字读取字符串?

c# - WPF MVVM : how to bind GridViewColumn to ViewModel-Collection?

c# - 创建可以绑定(bind)到 DataGrid 的自定义集合

c# - TabItem 绑定(bind) WPF

c# - 在 RichTextBox 中对行进行排序的最佳方法是什么

wpf - 在 Telerik RadView 中向列标题添加按钮

wpf - 如何强制 MarkupExtension 再次绑定(bind)

java - Struts2如何将Set<Object>从 View 绑定(bind)回 Controller