首页 > 解决方案 > 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;
    }
}

标签: c#wpf

解决方案


您需要使用 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 文章中的链接更详细地解释了这一点。

另外:我猜您使用线程时遇到的异常可能是调度异常。这是一篇很好的文章,可以帮助您了解如何解决这个问题。


推荐阅读