I want to set items(UserControl) to ItemsControl using multithread. My code likes this
System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(SetItemsControl));
thread.Start();
void SetItemsControl()
{
IDictionary<string, object> list = GetUserControlList(); // this function return list of UserControl
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate()
{
mylistcontrol.ItemsSource = list;
}));
}
And it breaks at my initialize function of my usercontrol
The calling thread must be STA, because many UI components require this.
How can i fix it??
The right way to do it is to update the collection that is bound to
ItemsControl.ItemsSource. In this scenario you do not touch the visual element from another thread – you update the collection that is bound to it. The collection being updated tells the binding to refresh and that’s when data comes to UI, and it happens already in UI thread so it’s ok. Note that collection should implementINotifyCollectionChangedinterface to be able to do that