2

これは、前の質問の回答に基づくフォローアップです。タイマーを使用して常に最新の日時になるように更新されるDependencyPropertyと、日時を示すテキストブロックを思い付くことができました。これはDependencyPropertyであるため、タイマーが値を更新するたびに、テキストブロックには最新の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;
        }

    }

ウィンドウXaml

    <Window.DataContext>
        <local:TestDependency/>
    </Window.DataContext>
    <Grid>
        <TextBlock Text="{Binding TestDateTime}" />
    </Grid>

これは非常にうまく機能しますが、時間文字列を別の方法でフォーマットしたい場合はToString(formatter)、テキストブロックに表示する前に日時を呼び出す方法がありますが、 DependencyPropertyを使用してテキストブロックを自動更新する機能?コードビハインドでこれを行う正しい方法と、可能であればXamlでこれを行う正しい方法は何ですか?

また、表示する複数のテキストボックスがあり、それぞれが異なる日時形式である場合、1つのタイマーだけを使用して、さまざまなテキストボックスにすべての異なる日時形式を表示する適切な方法は何ですか?それぞれの単一のフォーマット?

4

2 に答える 2

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()を使用する必要があると思います。理由は、ここで読むことができます。

private void Callback(object ignore, EventArgs ex)
{
    SetCurrentValue(TestDateTimeProperty, DateTime.Now);
}
于 2013-02-05T11:29:14.000 に答える
1

バインディングにはStringFormatプロパティがあります。

<TextBlock Text="{Binding TestDateTime, StringFormat=HH:mm:ss}"/>

標準の日付と時刻の形式の文字列およびカスタムの日付と時刻の形式の文字列も参照してください。

于 2013-02-05T11:32:27.040 に答える