WPF用户控件子级不更新c#

时间:2016-02-02 09:26:00

标签: c# wpf asynchronous

我正在尝试将一个子控件(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*/
}

1 个答案:

答案 0 :(得分:3)

您的功能是在后台工作程序中执行的:在Dispatcher Thread中没有完成。每次使用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)

相关问题