Updating UI with BackgroundWorker in WPF

后端 未结 3 558
生来不讨喜
生来不讨喜 2020-12-19 02:23

I am currently writing a simple WPF 3.5 application that utilizes the SharePoint COM to make calls to SharePoint sites and generate Group and User information. Since this pr

3条回答
  •  心在旅途
    2020-12-19 02:58

    At first you need to support ProgressChanged events. Update your BackgroundWorker initialization to:

    GroupListView.ItemSource = null;
    mWorker = new BackgroundWorker();
    mWorker.DoWork += new DoWorkEventHandler(worker_DoWork);
    mWorker.WorkerSupportsCancellation = true;
    mWorker.WorkerReportsProgress = true;
    mWorker.ProgressChanged += OnProgressChanged;
    mWorker.RunWorkerCompleted +=
            new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
    mWorker.RunWorkerAsync(SiteURLTextBox.Text);
    

    After that you have to add a OnProgressChanged handler:

    private void OnProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        FetchDataProgressBar.Value = e.ProgressPercentage;
        ListViewItem toAdd = (ListViewItem)e.UserState;
        toAdd.MouseLeftButtonUp += item_MouseLeftButtonUp;
        GroupListView.Items.Add(toAdd);
    }
    

    Therefore you have to change your DoWork:

    private void worker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
    {
        BackgroundWorker worker = (BackgroundWorker)sender;            
        try
        {
            using (SPSite site = new SPSite((String)e.Argument))
            {
                SPWeb web = site.OpenWeb();
                SPGroupCollection collGroups = web.SiteGroups;
                if(GroupNames == null)
                    GroupNames = new List();
                int added = 0;
                foreach(SPGroup oGroup in collGroups)
                {
                    added++;
                    ListViewItem tmp = new ListViewItem() {
                        Content = oGroup.Name
                    };
                    worker.ReportProgress((added * 100)/collGroups.Count,tmp);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to locate a SharePoint site at: " + siteUrl);
        }
    }
    

    That's because you're not allowed to change GUI on DoWork.

    After that, each ListViewItem is added separately to your ListView. I would also recommend, that your URL is passed as an argument to RunWorkerAsync.

    Edit: Add percentage to OnProgressChanged.

提交回复
热议问题