繁体   English   中英

如何从另一个类更新窗口应用程序中的进度条?

[英]How can i update the progress bar in window application from another class?

我创建了一个Windows窗体,那里有一个进度条,我想从另一个类更新进度条的值。 我已经在我的课程的执行中编写了一个函数,我想查看进度条。

例如:

  1. 以.cs文件形式编写的代码:
 namespace UpdateProgressBar
{
    public partial class ProgressBarUdpate : Form
    {
        public ProgressBarUdpate()
        {
            InitializeComponent();
        }

        private void btn_Submit_Click(object sender, EventArgs e)
        {
            UpdateDataProgress updt = new UpdateDataProgress();
            updt.ExecuteFucntion();
        }
    }
}
  1. 用另一类编写的代码
namespace UpdateProgress
{
    public class UpdateDataProgress
    {
        public void ExecuteFucntion()
        {
            for (int i = 0; i < 100; i++)
            {

            }

        }
    }
}

我的预期输出是当我调用updt.ExecuteFucntion函数时,它应根据在另一个类中实现的循环更新进度条的值。

您应在此类要求中使用Event

逻辑:

因为您的基本要求是根据方法的当前执行状态(位于类库中)更新ProgressbarUI

您需要在执行ExecuteFucntion()时引发一个事件。 此事件将在ProgressBarUdpate表单中处理。

如下面的代码所示,在创建UpdateDataProgress对象后,我们通过updt.ExecutionDone += updt_ExecutionDone;预订了该事件updt.ExecutionDone += updt_ExecutionDone;

因此,一旦该事件从ExecuteFucntion()引发,它将调用ProgressBarUdpate updt_ExecutionDone ,您可以在其中逐步更新进度条。

如下更新代码。

    public partial class ProgressBarUdpate : Form
    {
        public ProgressBarUdpate()
        {
            InitializeComponent();
        }

        private void btn_Submit_Click(object sender, EventArgs e)
        {
            UpdateDataProgress updt = new UpdateDataProgress();
            updt.ExecutionDone += updt_ExecutionDone;
            updt.ExecuteFucntion();
        }

        void updt_ExecutionDone(int value)
        {
            //Update your progress bar here as per value
        }
    }

和类UpdateProgress

    public delegate void ExceutionHandler(int value);
    public class UpdateDataProgress
    {
        public event ExceutionHandler ExecutionDone;
        public void ExecuteFucntion()
        {
            for (int i = 0; i < 100; i++)
            {
                //perform your logic

                //raise an event which will have current i 
                //      to indicate current state of execution
                //      use this event to update progress bar 

                if (ExecutionDone != null)
                    ExecutionDone(i);
            }

        }
    }

您可以使用事件,也可以简单地:

  1. 代码形式:

     private void btn_Submit_Click(object sender, EventArgs e) { UpdateProgress.UpdateDataProgress updt = new UpdateProgress.UpdateDataProgress(); updt.ExecuteFucntion(progressBar1); } 
  2. 班级代码:

     public class UpdateDataProgress { public void ExecuteFucntion(System.Windows.Forms.ProgressBar progbar) { for (int i = 0; i < 100; i++) { progbar.Value = i; } } } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM