这种类型的CollectionView不支持从与Dispatcher线程不同的线程对其

这种类型的CollectionView不支持从与Dispatcher线程不同的线程对其SourceCollection进行更改

我有一个DataGrid通过异步方法从ViewModel填充数据。我的DataGrid是:


<DataGrid ItemsSource="{Binding MatchObsCollection}"  x:Name="dataGridParent" 

                      Style="{StaticResource EfesDataGridStyle}" 

                      HorizontalGridLinesBrush="#DADADA" VerticalGridLinesBrush="#DADADA" Cursor="Hand" AutoGenerateColumns="False" 

                      RowDetailsVisibilityMode="Visible"  >

我正在使用http://www.amazedsaint.com/2010/10/asynchronous-delegate-command-for-your.html在我的视图模型中实现异步方式。


这是我的视图模型代码:


public class MainWindowViewModel:WorkspaceViewModel,INotifyCollectionChanged

    {        


        MatchBLL matchBLL = new MatchBLL();

        EfesBetServiceReference.EfesBetClient proxy = new EfesBetClient();


        public ICommand DoSomethingCommand { get; set; }

        public MainWindowViewModel()

        {

            DoSomethingCommand = new AsyncDelegateCommand(

                () => Load(), null, null,

                (ex) => Debug.WriteLine(ex.Message));           

            _matchObsCollection = new ObservableCollection<EfesBet.DataContract.GetMatchDetailsDC>();                


        }       


        List<EfesBet.DataContract.GetMatchDetailsDC> matchList;

        ObservableCollection<EfesBet.DataContract.GetMatchDetailsDC> _matchObsCollection;


        public ObservableCollection<EfesBet.DataContract.GetMatchDetailsDC> MatchObsCollection

        {

            get { return _matchObsCollection; }

            set

            {

                _matchObsCollection = value;

                OnPropertyChanged("MatchObsCollection");

            }

        }        

 

正如您在ViewModel的Load()方法中看到的那样,首先从服务中获取matchList(这是DataContract类的列表),然后通过foreach循环将我的matchList项插入到_matchObsCollection(这是一个ObservableCollection)中DataContract类))。现在,我收到上述错误(如标题所示)“此CollectionView类型不支持从与Dispatcher线程不同的线程对其SourceCollection进行更改” 在此处输入图片说明


任何人都可以向我提出任何解决方案。此外,如果可能的话,我想知道如何在View中绑定我的DataGrid,并且如果有更好的方法,还可以异步刷新它。


当年话下
浏览 2256回答 3
3回答

梦里花落0921

由于您的ObservableCollection是在UI线程上创建的,因此您只能从UI线程而不是其他线程进行修改。这被称为线程亲和力。如果您需要从不同的线程更新在UI线程上创建的对象,只需简单地put the delegate on UI Dispatcher这样做就可以将其委托给UI线程。这将起作用-&nbsp; &nbsp; public void Load()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; matchList = new List<GetMatchDetailsDC>();&nbsp; &nbsp; &nbsp; &nbsp; matchList = proxy.GetMatch().ToList();&nbsp; &nbsp; &nbsp; &nbsp; foreach (EfesBet.DataContract.GetMatchDetailsDC match in matchList)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; App.Current.Dispatcher.Invoke((Action)delegate // <--- HERE&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _matchObsCollection.Add(match);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP