无法从另一个线程将 child 添加到 WrapPanel

Can't add child to WrapPanel from another thread

我是线程任务的新手,所以很明显为什么我不能做我正在做的事情。我不明白为什么我可以在我的线程中更改 WrapPanelWidth,但我不能向其中添加 child。这是我的代码:

private void Grid_Loaded(object sender, RoutedEventArgs e)
{
     Thread t = new Thread(LoadIcons);
     t.SetApartmentState(ApartmentState.STA);

     t.Start();
}

private void LoadIcons()
{ 
     Foreach(icon present in directory)
     {
        Icon icon = new Icon { Width = 16, Height = 16};

        Dispatcher.Invoke(new Action(() => pnlIcons.Width = 50)); //Will let me
        Dispatcher.Invoke(new Action(() => pnlIcons.Children.Add(icon))); // Won't
     }
}

您必须重写您的代码。将 图标 放在 Dispatcher 中以避免异常。

private void Grid_Loaded(object sender, RoutedEventArgs e)
{
    Thread t = new Thread(LoadIcons);
    t.SetApartmentState(ApartmentState.STA);

    t.Start();
}

private void LoadIcons()
{ 
    Dispatcher.Invoke(new Action(() => 
    {
        foreach(Icon present in directory)
        { 
            present.Width = 16;
            present.Height = 16;
            pnlIcons.Width = 50;
            pnlIcons.Children.Add(present);
        }
    }));
}  

希望对您有所帮助。