WPF:将dependencyproperty格式化为字符串以在文本块中显示的正确方法是什么?

bla*_*pea 2 wpf wpf-controls

这是基于前一个问题的答案的跟进.我设法提出了一个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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

窗口Xaml

    <Window.DataContext>
        <local:TestDependency/>
    </Window.DataContext>
    <Grid>
        <TextBlock Text="{Binding TestDateTime}" />
    </Grid>
Run Code Online (Sandbox Code Playgroud)

这非常有效,但我想知道,如果我想以不同的方式格式化时间字符串,我该怎么办?有没有办法ToString(formatter)在显示文本块之前调用日期时间,同时保持能否使用DependencyProperty自动更新文本块?在后面的代码中执行此操作的正确方法是什么,以及在Xaml中执行此操作的正确方法,如果可能的话?

而且,如果我有多个文本框显示,每个文本框都有不同的日期时间格式,使用只有1个计时器在不同的文本框中显示所有不同的日期时间格式的正确方法是什么,我是否必须创建一个DependencyProperty for每种格式?

Joh*_*son 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>
Run Code Online (Sandbox Code Playgroud)

另外我认为你应该在更新DependencyProperty时使用SetCurrentValue(),你可以在这里阅读原因

private void Callback(object ignore, EventArgs ex)
{
    SetCurrentValue(TestDateTimeProperty, DateTime.Now);
}
Run Code Online (Sandbox Code Playgroud)