将百分比文本添加到进度条 C# [英] Adding percentage text to progressbar C#

查看:42
本文介绍了将百分比文本添加到进度条 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法可以显示进程栏何时正在执行以及何时成功完成.

I have a method that shows when a process bar is in execution and when is successfully completed.

我工作得很好,但我想添加一个百分比,如果完成则显示 100%,如果它卡在某个地方,则显示更少.

I worked fine, but I would like to add a percentage showing a 100% if is complete and less if it got stuck some where.

我在网上做了一些研究,但我无法适应我正在寻找的解决方案.

I have made several research online but I could not adapt anything to the solution that I am looking for.

这是我的代码:

private void progressBar()
{
    int i;

    progressBar1.Minimum = 0;
    progressBar1.Maximum = 100;

    for (i = 0; i <= 100; i++)
    {
        progressBar1.Value = i;               
    }
}

我在执行按钮上使用方法调用,方法如下:

I use the method call on my execution button by calling it with the follow:

progressBar();

谢谢

推荐答案

为了在您的操作中实现进度,必须先计算操作的长度.如果不可能,则无法显示该操作的进度条.(也许只是一个加载 gif)

In order to implement the progress in your operation, the operation's length must be calculated first. if it's not possible, you can't show a progress bar for that operation. (maybe only a loading gif)

但如果是这样,有一个界面 (IProgress) 可以帮助您实施进度报告.

but if so, There is an interface (IProgress) which can help you implement the progress reports.

首先你应该知道,你必须在另一个线程上完成主要任务,并将进度报告给 UI 线程.这项工作的一个简单例子是这样的.

First thing you should know, You must do the main task on another thread, and report the progress to the UI Thread. a simple example of this work would be something like this.

Progress.cs

Progress.cs

public class Progress<T> : IProgress<T>
{
    private readonly Action<T> _progressAction;

    public Progress(Action<T> action)
    {
        _progressAction = action;
    }

    public void Report(T value)
    {
        _progressAction?.Invoke(value);
    }
}

你的代码应该是这样的,在你点击一个名为 ButtonBase 的按钮后任务开始

Your code would be like this, in which the task starts after you click a button named ButtonBase

Progress<int> MyProgressObject { get; set; }

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    MyProgressObject = new Progress<int>(ProgressAction);
    ThreadPool.QueueUserWorkItem(TimeConsumingTask);
}

public void TimeConsumingTask(object state)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(100);
        MyProgressBar.Dispatcher.Invoke(() => ProgressAction(i));
    }
}

public void ProgressAction(int progress)
{
    MyProgressBar.Value = progress;
}

我知道这可能看起来很困难,但这是完成耗时任务并防止 UI 阻塞的正确方法

I know It might look difficult but this is the proper way of doing time consuming tasks and prevent UI block

这篇关于将百分比文本添加到进度条 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆