0
Answer

How to add UIElement to UI on a separate thread in WPF?

Liviu  Mihail

Liviu Mihail

16y
7k
1
What I want to do:
into a Grid, I want to add 2 UserControl's at runtime.
Every control can stop to respond to a user input at a time (on an action inside control). But in the same time, I want to be able to work with the second control.
For this, I think is needed to create every control on a separate thread.
When I want to add this controls to grid I receive this error:
"The calling thread cannot access this object because a different thread owns it."

this is my code:
private void function MainFunc()
{
    //add first control  to grid
    NewPanelThread();
    //add second to grid
    NewPanelThread();
 }

private void NewPanelThread()
{
     Thread thre = new Thread(new ThreadStart(AddPanel));
     thre.SetApartmentState(ApartmentState.STA);
     thre.IsBackground = true;
     thre.Start();
}

private void AddPanel()
{
       UserControl dPanel = new UserControl ();
       Dispatcher.BeginInvoke(DispatcherPriority.Normal, new    OneArgDelegate(UpdateUserInterface), dPanel);
        System.Windows.Threading.Dispatcher.Run();
}

private delegate void OneArgDelegate(UserControl  myControl);

 private void UpdateUserInterface(UserControl  objPanel)
{
        MyGrid.Children.Add(objPanel);
}