这是基于上一个问题的answer的跟进。我设法提出了一个DependencyProperty,它将使用Timer更新,以便始终拥有最新的日期时间,以及一个显示日期时间的文本块。由于它是DependencyProperty,每当定时器更新值时,textblock也会显示最新的DateTime。
依赖对象
public class TestDependency : DependencyObject
{
public static readonly DependencyProperty TestDateTimeProperty =
DependencyProperty.Register("TestDateTime", typeof(DateTime), typeof(TestDependency),
new PropertyMetadata(DateTime.Now));
DispatcherTimer timer;
public TestDependency()
{
timer = new DispatcherTimer(new TimeSpan(0,0,1), DispatcherPriority.DataBind, new EventHandler(Callback), Application.Current.Dispatcher);
timer.Start();
}
public DateTime TestDateTime
{
get { return (DateTime)GetValue(TestDateTimeProperty); }
set { SetValue(TestDateTimeProperty, value); }
}
private void Callback(object ignore, EventArgs ex)
{
TestDateTime = DateTime.Now;
}
}
Window Xaml
<Window.DataContext>
<local:TestDependency/>
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding TestDateTime}" />
</Grid>
这非常有效,但我想知道,如果我想以不同的方式格式化时间字符串,我该怎么办?有没有办法在显示之前调用日期时间ToString(formatter)
它在textblock中,同时保持使用DependencyProperty自动更新文本块的能力?在后面的代码中执行此操作的正确方法是什么,以及在Xaml中执行此操作的正确方法,如果可能的话?
而且,如果我要显示多个文本框,每个文本框都有不同的日期时间格式,使用仅1个计时器在不同文本框中显示所有不同日期时间格式的正确方法是什么,我是否必须创建每种格式的DependencyProperty?
答案 0 :(得分:6)
您可以使用字符串格式:
<Window.DataContext>
<wpfGridMisc:TestDependency/>
</Window.DataContext>
<StackPanel>
<TextBlock Text="{Binding TestDateTime, StringFormat=HH:mm:ss}"/>
<TextBlock Text="{Binding TestDateTime, StringFormat=MM/dd/yyyy}"/>
<TextBlock Text="{Binding TestDateTime, StringFormat=MM/dd/yyyy hh:mm tt}"/>
<TextBlock Text="{Binding TestDateTime, StringFormat=hh:mm tt}"/>
<TextBlock Text="{Binding TestDateTime, StringFormat=hh:mm}"/>
<TextBlock Text="{Binding TestDateTime, StringFormat=hh:mm:ss}"/>
</StackPanel>
另外我认为你应该在更新DependencyProperty时使用SetCurrentValue(),你可以阅读为什么here
private void Callback(object ignore, EventArgs ex)
{
SetCurrentValue(TestDateTimeProperty, DateTime.Now);
}
答案 1 :(得分:1)
绑定具有StringFormat属性:
<TextBlock Text="{Binding TestDateTime, StringFormat=HH:mm:ss}"/>
另请参阅Standard Date and Time Format Strings和Custom Date and Time Format Strings。