【问题标题】:WPF - Canvas won't update when BackgroundWorker is completedWPF - BackgroundWorker 完成后画布不会更新
【发布时间】:2015-10-19 14:03:43
【问题描述】:

BackgroundWorker 完成后,我需要更新我的 Canvas。当我通过按钮动作监听器更新画布时,它工作得很好。但是当我在 backroundWorker 完成时调用我的更新函数时。 gui不会更新。

向画布添加项目的函数:

public void AddItemsToCanvas()
    {

       int factor = 0;

       cvList.Children.Clear();
       foreach (ItemControl item in ItemControl.ItemsList)
       {

           cvList.Children.Add(item.updateName);
           Canvas.SetLeft(item.updateName, 13);
           Canvas.SetTop(item.updateName, factor + 10);
           Canvas.SetZIndex(item.updateName, 1);

           cvList.Children.Add(item.imageButton);
           Canvas.SetLeft(item.imageButton, 180);
           Canvas.SetTop(item.imageButton, factor + 13);
           Canvas.SetZIndex(item.imageButton, 5);}}

调用更新函数的按钮:

private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        updateCanvas();
    }

    public void updateCanvas()
    {
            Service serv = new Service();
            serv.SuperlinkCompartments();

            //Check for updates and add them to a List of updates
            Update up = new Update();
            up.PropertyChanged += new PropertyChangedEventHandler(Items_PropertyChanged);
            up.ShowUpdates();      
    }

    public void Items_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        AddItemsToCanvas();
    }

当从按钮 actionListener 调用时,Canvas 会完美更新。但是当从 BackgroundWorker 事件调用 UpdateCanvas() 时不起作用。

public void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        var item = dic3[(BackgroundWorker)sender];
        int index = (int)item.controlButton.Tag;
        item.Progressbar.Value = 0;

        SystemInfo.SystemList[Update.UpdateList[index].SystemIndex].Version = Update.UpdateList[index].UpdateVersion;


        lvSystems.ItemsSource = SystemInfo.SystemList;

        updateCanvas();

    }

我在 BackgroundWorker 事件函数中遗漏了什么?

【问题讨论】:

  • 我尝试在我的代码中包含 Dispatcher.BeginInvoke。但不能让它工作。

标签: wpf multithreading user-interface canvas


【解决方案1】:

尝试使用 `Dispatcher':

Application.Current.Dispatcher.Invoke(new Action(()=>
{
    updateCanvas();
}), DispatcherPriority.Render);

然后,在您的 updateCanvas() 方法中,在末尾添加以下内容:

cvList.UpdateLayout();

【讨论】:

  • 你有其他建议@d.moncada 吗?
  • @user3000138 添加了更新。尝试在 backgroundWorker1_RunWorkerCompleted 方法中使用 Application.Current.Dispatcher,然后在 updateCanvas() 末尾添加 UpdateLayout
  • 还是不行。我想我在某个地方遇到了线程问题。 @d.moncada
  • 有趣.. 什么时候调用后台工作人员,什么时候?另外,为什么要使用后台工作人员?
  • background.RunWorkerAsync 是从位于我的画布内的按钮调用的。我的按钮的 actionListener 位于 MainWindow 中。我还从按钮 actionListener 初始化我的后台工作人员。我正在使用后台工作人员在进度条中报告进度。这是一个提取一些文件并将它们复制到不同位置的功能。我使用它来报告进度的唯一目的是因为它可能是一个漫长的过程,我不希望它为我的 UI 线程阻塞。 d.moncada
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多