【问题标题】:WPF User Control children not updating c#WPF用户控件子级不更新c#
【发布时间】:2016-02-02 09:26:00
【问题描述】:

我正在尝试将子控件 (UserControl) 添加到 Grid 并且更改未反映。但是,如果将另一个子控件 (UserControl) 添加到同一个网格中,则布局会更新并且两个子控件都可见。此操作在按钮单击时执行。

/*this Operation is perform in Backgroud Worker */
void func()
{
    /*adding first User Control*/
    addRemoveChild(true,FirstChild);//even tried to run this fuc with Dispatcher    
    FixButton();
    addRemoveChild(false,FirstChild);
}

void addRemoveChild(bool isAdd,UserControl uc)
{
    if (isAdd)
    {
        parentGrid.Children.Add(uc);         /*parentGrid is Parent Grid*/
        parentGrid.UpdateLayout();

        return;
    }
    else
    {            
        parentGrid.Children.Remove(uc);
        parentGrid.UpdateLayout();
    }
}

void FixButton()
{
    /* here some operation is perform which takes 5 min to complete till then FirstChild is not visible*/

    addRemoveChild(true,secondChild);                              /*When this Func run the first Child is visible*/
}

【问题讨论】:

  • 确保您的 UI 线程不会因为 FixButton() 方法中的 5 分钟操作而被阻塞
  • 并尝试评论那 5 分钟的操作并检查会发生什么?
  • 你最好更新你的整个代码,包括 5 分钟的操作..

标签: c# wpf asynchronous


【解决方案1】:

您的功能是在后台工作人员中执行的:它不是在调度程序线程中完成的。每次使用 Dispatcher 对象(由 Dispatcher 线程创建的对象,例如 Controls)时,您都应该在 Dispatcher 线程中。

后台工作人员可用于“实时”执行任务和更新相对于任务状态的 UI。

您没有正确使用后台工作程序。 DoWork 中的代码在单独的线程中执行,而 ProgressChanged 回调在 Dispatcher 线程中执行。

你的代码应该是这样的:

BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (sender, args) => {
    bw.ReportProgress(0);
    FixButton();
    bw.ReportProgress(100);
};

bw.ProgressChanged += (sender, args) => {
    if (args.ProgressPercentage == 0) {
        parentGrid.Children.Add(uc);
    } else if(args.ProgressPercentage == 100) {
        parentGrid.Children.Remove(uc);
    }
};

bw.RunWorkerAsync();

顺便说一句,您不需要调用 UpdateLayout() 并且您的 DoWork 回调函数不应该使用 Dispatcher 对象(从 FixButton 函数中删除 addRemoveChild)

【讨论】:

  • 确实是一样的,但作为替代方案,也可以使用 Task.Run。你可以用 Async 和 Await 做很多事情。
猜你喜欢
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 2010-09-23
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多