特定の時間のかかるタスクのステータスを表示する WPF アプリケーションを作成しています。
タスクの開始時間にバインドされた TextBlock があり、そのタスクに費やされた時間を表示するための別の TextBlock があります。
コンバーターを使用した単純なバインドを使用して、2 番目の TextBlock を取得して TimeSpan を適切に表示することができましたが、このソリューションにあまり夢中ではありません。時間の経過とともに 2 番目の TextBlock で TimeSpan を更新したいと思います。
たとえば、ユーザーがアプリケーションをロードすると、2 番目の TextBlock は「5 分」と表示されますが、15 分後も「5 分」と表示されるため、誤解を招きます。
私はこの解決策 ( Binding to DateTime.Now. Update the value )を見つけることができました。
タスクの開始時間をこの Ticker クラスに渡して、テキスト自体を更新する方法はありますか?
編集:これが私がこれまでに持っているものです:
C#:
public class Ticker : INotifyPropertyChanged { public static DateTime StartTime { get; 設定; }
public Ticker()
{
Timer timer = new Timer();
timer.Interval = 1000;
timer.Elapsed += timer_Elapsed;
timer.Start();
}
public string TimeDifference
{
get
{
string timetaken = "";
try
{
TimeSpan ts = DateTime.Now - StartTime;
timetaken = (StartTime == default(DateTime)) ? "StartTime not set!" : ((ts.Days * 24) + ts.Hours).ToString("N0") + " hours, " + ts.Minutes + " minutes, " + ts.Seconds + " seconds";
}
catch (Exception) { }
return timetaken;
}
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("TimeDifference"));
}
public event PropertyChangedEventHandler PropertyChanged;
}
XAML:
<StackPanel Grid.Row="2" Grid.Column="0" Orientation="Horizontal">
<TextBlock Text="Dataset started on:"/>
<TextBlock Name="starttimeLabel" Text="10/23/2012 4:42:26 PM"/>
</StackPanel>
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="Time taken:"/>
<TextBlock Name="timespanLabel" Text="{Binding Source={StaticResource ticker}, Path=TimeDifference, Mode=OneWay}"/>
</StackPanel>
最後に、私の StatusPanel の Loaded イベントには、次のものがあります。
Ticker.StartTime = Convert.ToDateTime(starttimeLabel.Text);
ひどい書式設定で申し訳ありませんが、指示に従ってみましたが役に立ちませんでした (コード ブロックに 4 つのスペースを挿入して<code></code>
から、などを使用してみました)。