これは、前の質問の回答に基づくフォローアップです。タイマーを使用して常に最新の日時になるように更新される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つのタイマーだけを使用して、さまざまなテキストボックスにすべての異なる日時形式を表示する適切な方法は何ですか?それぞれの単一のフォーマット?