【发布时间】:2012-10-17 16:23:59
【问题描述】:
我正在编写一个显示某个耗时任务状态的 WPF 应用程序。
我有一个绑定到任务开始时间的 TextBlock,我还有另一个 TextBlock,用于显示在所述任务上花费的时间。
使用与转换器的简单绑定,我能够让第二个 TextBlock 正确显示 TimeSpan,但我对这个解决方案并不太感兴趣。我希望第二个 TextBlock 随着时间的推移更新 TimeSpan。
例如,当用户加载应用程序时,第二个 TextBlock 会说“5 分钟”,但 15 分钟后,它仍然会说“5 分钟”,这是一种误导。
我能够找到这个解决方案 (Binding to DateTime.Now. Update the value),它非常接近我想要的,但并不完全在那里。
有什么方法可以将任务的开始时间传递给这个 Ticker 类并让文本自行更新?
编辑:这是我目前所拥有的:
C#:
公共类代码:INotifyPropertyChanged
{
公共静态日期时间开始时间{获取;放; }
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> 等)
【问题讨论】:
-
任务是什么意思?你能添加一些代码吗?
-
在这种情况下“任务”的定义不会影响答案。但是,任务涉及在一组计算机上生成数百万张图像,因此可能需要几天时间。这就是为什么我不想显示任务处理的时间量。