WPF:将dependencyproperty格式化为字符串以显示在文本块中的正确方法是什么?
这是基于前一个问题的结论的后续行动。我已经设法想出了一个DependencyProperty,它将使用计时器进行更新,以始终具有最新的日期时间,以及一个显示日期时间的文本块。由于它是一个DependencyProperty,每当计时器更新值时,textblock也将显示最新的日期时间 依赖项对象WPF:将dependencyproperty格式化为字符串以显示在文本块中的正确方法是什么?,wpf,wpf-controls,Wpf,Wpf Controls,这是基于前一个问题的结论的后续行动。我已经设法想出了一个DependencyProperty,它将使用计时器进行更新,以始终具有最新的日期时间,以及一个显示日期时间的文本块。由于它是一个DependencyProperty,每当计时器更新值时,textblock也将显示最新的日期时间 依赖项对象 public class TestDependency : DependencyObject { public static readonly DependencyPro
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;
}
}
窗口Xaml
<Window.DataContext>
<local:TestDependency/>
</Window.DataContext>
<Grid>
<TextBlock Text="{Binding TestDateTime}" />
</Grid>
这工作得很好,但我想知道,如果我想以不同的方式格式化时间字符串,我该怎么做,有没有办法在日期时间上调用ToString(格式化程序)
,然后再将其显示在textblock中,同时保持使用DependencyProperty自动更新textblock的能力?如果可能的话,在代码隐藏中正确的方法是什么,在Xaml中正确的方法是什么
而且,如果我要显示多个文本框,每个文本框都有不同的日期时间格式,那么使用一个计时器在不同的文本框中显示所有不同的日期时间格式的正确方法是什么,我是否必须为每个格式创建DependencyProperty?您可以使用字符串格式:
<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>
绑定有一个属性:
<TextBlock Text="{Binding TestDateTime, StringFormat=HH:mm:ss}"/>
另见和
<TextBlock Text="{Binding TestDateTime, StringFormat=HH:mm:ss}"/>