嗯,我需要将 DateTime.Now 绑定到 TextBlock,我使用了它:
Text="{Binding Source={x:Static System:DateTime.Now},StringFormat='HH:mm:ss tt'}"
现在,如何强制更新?这是加载控件的时间,并且不会更新它......
这里是“Ticker”类的链接,它使用 INotifyPropertyChanged,因此它会自动更新。这是该网站的代码:
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}"/>
对于 Windows Phone,您可以使用此代码片段
public Timer()
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(1); // 1 second updates
timer.Tick += timer_Tick;
timer.Start();
}
public DateTime Now
{
get { return DateTime.Now; }
}
void timer_Tick(object sender, EventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Now"));
}
public event PropertyChangedEventHandler PropertyChanged;
我改编了m-y的代码。希望这个也能有用。
您需要制作一个每秒更新文本框的计时器。
事实上,执行此操作的“规范”方法是设置 DispatcherTimer
但是,您也可以使用故事板和假转换器来完成此操作,如下所示:
<Storyboard x:Key="clockStory" Duration="0:0:2" RepeatBehavior="Forever">
<StringAnimationUsingKeyFrames
Storyboard.TargetName="clock"
Storyboard.TargetProperty="(Label.Tag)">
<DiscreteStringKeyFrame KeyTime="0:0:0" Value="Let's force binding" />
<DiscreteStringKeyFrame KeyTime="0:0:1" Value="..to change back and forth" />
</StringAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded">
<BeginStoryboard Storyboard="{StaticResource clockStory}"/>
</EventTrigger>
</Window.Triggers>
<Grid>
<Label x:Name="clock" Content="{Binding ElementName=clock, Path=Tag, Converter={StaticResource conv}}"/>
</Grid>
..转换器如下
public class AnythingToCurrentTimeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return DateTime.Now.ToString("HH:mm:ss");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
享受吧!
添加到此answer,如果您想格式化返回的时间: 您可以通过这样的标签来做到这一点:
<Label Content="{Binding Source={StaticResource ticker} ,Path=Now, Mode=OneWay}" ContentStringFormat="dd-MM-yyyy HH:mm"/>
并根据需要更改您的
ContentStringFormat