簡體   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