如何使用多线程将Usercontrol添加到ItemsControl?

时间:2012-05-03 10:02:52

标签: wpf multithreading user-controls

我想使用多线程将项目(UserControl)设置为ItemsControl。我的代码喜欢这个

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;

            }));
    }

它在我的usercontrol的初始化函数中断了

  

调用线程必须是STA,因为许多UI组件都需要这个。

我该如何解决?

1 个答案:

答案 0 :(得分:2)

正确的方法是更新绑定到ItemsControl.ItemsSource的集合。在这种情况下,您不会触摸另一个线程中的可视元素 - 您更新绑定到它的集合。正在更新的集合告诉绑定刷新以及数据到达UI时的情况,并且它已经在UI线程中发生,因此它没有问题。请注意,集合应该实现INotifyCollectionChanged接口以便能够执行此操作

相关问题