c# - Display information on screen during process
问题描述
I want to display information on screen for the user general view about process!
In the beginning, I used another thread, but this started an exception. Now I don't know. How can I change value on the screen simultaneously with another process?
How can I use GetElapsedTime to Show millisecond elapsed during the process?
WPF (XAML Code)
<StackPanel>
<Button Content="Start" Height="20" Width="50" HorizontalAlignment="Left" Name="ButtonStart" Click="ButtonStart_Click"/>
<Label Content="Elapsed Time (Milliseconds):"/>
<Label Name="LabelElapsedTime" Content="0"/>
</StackPanel>
public partial class MainWindow : Window
{
private StatusOfWork _StatusOfWork;
public MainWindow()
{
InitializeComponent();
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
_StatusOfWork = new StatusOfWork();
_StatusOfWork.CountN(10);
this.Close();
}
}
class StatusOfWork
{
public DateTime StartDateTime { get; set; }
public void CountN(int nTimes)
{
StartDateTime = DateTime.Now;
for (int i = 1; i <= nTimes; i++)
{
//doing anything
//Another Process
//...
Thread.Sleep(1000);
}
}
public double GetElapsedTime()
{
TimeSpan timeSpan = DateTime.Now - StartDateTime;
return timeSpan.TotalMilliseconds;
}
}
解决方案
您需要使用 WPF 数据绑定概念。我建议查看这篇stackoverflow 文章,它有几个很好的链接到各种教程。
话虽如此,下面是对您的代码的更改,应该可以帮助您入门:我在您的标签上添加了一个LabelElapsedTime
名为LapsedTime
.
<StackPanel>
<Button Content="Start" Height="20" Width="50" HorizontalAlignment="Left" Name="ButtonStart" Click="ButtonStart_Click"/>
<Label Content="Elapsed Time (Milliseconds):"/>
<Label Name="LabelElapsedTime"
Content="{Binding ElapsedTime, RelativeSource={RelativeSource AncestorType=Window}}"/>
</StackPanel>
LapsedTime
并且绑定映射到主窗口上同名的依赖属性,如下所示:
public partial class MainWindow : Window
{
private StatusOfWork _StatusOfWork;
public MainWindow()
{
InitializeComponent();
}
public static readonly DependencyProperty ElapsedTimeProperty =
DependencyProperty.Register(nameof(ElapsedTime), typeof(string), typeof(MainWindow));
public string ElapsedTime
{
get { return (string)GetValue(ElapsedTimeProperty); }
set { SetValue(ElapsedTimeProperty, value); }
}
private async void ButtonStart_Click(object sender, RoutedEventArgs e)
{
for(int count = 0; count < 10; count ++)
{
ElapsedTime = string.Format("{0}", count);
await Task.Delay(1000);
}
this.Close();
}
}
为简单起见,我将属性保留为字符串,但您可能希望使用不同的数据类型。您将需要使用ValueConverter
. 上面提到的 stackoverflow 文章中的链接更详细地解释了这一点。
另外:我猜您使用线程时遇到的异常可能是调度异常。这是一篇很好的文章,可以帮助您了解如何解决这个问题。
推荐阅读
- sql - 多个键上的 FULL OUTER JOIN
- sorting - 如何根据模板类型的向量进行排序
- java - 如何在 List 中实例化和存储值
> - python - 如何有效地计算可能组合的数量(在每种类型中至少选择一种时)?
- vue.js - 在组件加载时显示加载器
- android - 在 Facebook OAuth 身份验证过程中,如何在客户端保持相同的会话?
- r - 如何更改重要性条的位置以匹配填充比较?
- javascript - “当定位低于 ESNext 时,BigInt 文字不可用”
- java - Java FileInputStream 问题(额外的空格)
- r - 是否有一个函数可以帮助在 R 中使用 k-NN 预测缺失值?