嗯,我需要将 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/