如何从子类传递信息到我的主类

时间:2013-08-05 21:29:02

标签: c# wpf delegates

我有两个类,主要来自WPF,一个名为'PersistDataToTable'的子类在'PersistDataToTable.Persist'中我有一个循环,我想将该循环内容传递回主WPF类以显示在进度条中。 我有一个后台工作线程运行该方法来命中循环,我只是不知道如何从backgroundworker线程将数据返回到ReportProgress方法。

private void PersistDataToDb(object sender, RoutedEventArgs e)
    {
        worker = new BackgroundWorker();
        worker.WorkerReportsProgress = true;

        worker.DoWork += delegate(object o, DoWorkEventArgs args)
            {
                PersistDataToTable persistData = new PersistDataToTable();
                persistData.Persist(seriesId);

                worker.ReportProgress(loop incrament from persist()??);

            };

        worker.ProgressChanged += delegate(object o, ProgressChangedEventArgs args)
            { 
                int percentage = args.ProgressPercentage;
                progressBar.Value = percentage;
            };

        worker.RunWorkerAsync();
    }

2 个答案:

答案 0 :(得分:1)

您可以将worker.ReportProgress作为Action<Int>传递到Persist方法中,以便更新回您的用户界面

示例:

private void PersistDataToDb(object sender, RoutedEventArgs e)
{
    worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;

    worker.DoWork += delegate(object o, DoWorkEventArgs args)
        {
            PersistDataToTable persistData = new PersistDataToTable();
            persistData.Persist(seriesId, worker.ReportProgress);
        };

    worker.ProgressChanged += delegate(object o, ProgressChangedEventArgs args)
        {
            int percentage = args.ProgressPercentage;
            progressBar.Value = percentage;
        };

    worker.RunWorkerAsync();
}

public class PersistDataToTable
{
    public void Persist(int seriesId, Action<int> progresscallback)
    {

        // set the progress and call the Action(worker.ReportProgress)
        for (int i = 0; i < 100; i++)
        {
            progresscallback.Invoke(i);
        }
    }
}

答案 1 :(得分:0)

使用事件DoWork和RunWorkerComplete。这是一个计数到10并将结果传递给标签的示例:

void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    label1.Text = e.Result.ToString(); // getting the result set in DoWork
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
    int value = 0;

    for (int i = 0; i < 10; i++)
        value++;

    e.Result = value; // setting result for RunWorkerCompleted
}

msdn文章:http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.dowork.aspx