C# 如何从另一个类更新窗口应用程序中的进度条?
我已经创建了一个windows窗体,在那里我有一个进度条,我想从另一个类更新进度条的值。我已经在类中编写了一个函数来执行它,我想看看进度条中的进度 例如: 在forms.cs文件中编写的代码: 在另一个类中编写的代码C# 如何从另一个类更新窗口应用程序中的进度条?,c#,C#,我已经创建了一个windows窗体,在那里我有一个进度条,我想从另一个类更新进度条的值。我已经在类中编写了一个函数来执行它,我想看看进度条中的进度 例如: 在forms.cs文件中编写的代码: 在另一个类中编写的代码 我的预期输出是当我调用updt.executefuntion函数时,它应该根据在另一个类中实现的循环更新progressbar值。您可以使用事件,也可以简单地: 格式代码: private void btn_Submit_Click(object sender, EventArgs
我的预期输出是当我调用updt.executefuntion函数时,它应该根据在另一个类中实现的循环更新progressbar值。您可以使用事件,也可以简单地: 格式代码:
private void btn_Submit_Click(object sender, EventArgs e)
{
UpdateProgress.UpdateDataProgress updt = new UpdateProgress.UpdateDataProgress();
updt.ExecuteFucntion(progressBar1);
}
课堂代码:
public class UpdateDataProgress
{
public void ExecuteFucntion(System.Windows.Forms.ProgressBar progbar)
{
for (int i = 0; i < 100; i++)
{
progbar.Value = i;
}
}
}
您应该在此类需求中使用事件
逻辑:
因为您的基本需求是根据类库中方法的当前执行状态更新Progressbar UI
您需要在执行ExecuteFunction时引发事件。此事件将以ProgressBarUdpate表单处理
正如您在下面的代码中所看到的,在创建UpdateDataProgress的对象之后,我们通过updt.ExecutionDone+=updt_ExecutionDone订阅它的事件
因此,一旦该事件从executefunction表单中引发,它将调用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
活动是一个很好的方式。你能发送一些样本吗?可能的副本也是事实上我有两个项目在同一个解决方案Windows应用程序和类库中,我的另一个类在类库中。我可以在另一个库中也这样做吗?但是我的类在同一个解决方案中的另一个类库项目中。这在这种情况下有效吗?你真的genious@stackoverflow你会在这里看到很多更好的人。我很高兴能帮助你。活动和代表是非常有趣的话题。在这方面投入你的时间和精力。
public class UpdateDataProgress
{
public void ExecuteFucntion(System.Windows.Forms.ProgressBar progbar)
{
for (int i = 0; i < 100; i++)
{
progbar.Value = i;
}
}
}
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
}
}
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);
}
}
}