将项目添加到List< CustomClass>这是DataBinded到DataGrid [英] Adding an item to a List<CustomClass> which is DataBinded to a DataGrid
问题描述
基本上,我想做的是将新项目添加到具有DataBinded List<>的DataGrid中。我已经尝试了所有可能想到的方法,但是总是收到 An ItemsControl与它的项目源不一致的异常。如果有人可以帮助我,我将不胜感激。
Basically what I'am trying to do is to add a new Item into a DataGrid which has a DataBinded List<> to it. I already tried everything I could think of but I always get the "An ItemsControl is inconsistent with its items source" exception. If someone would help me with this I would be greatful
推荐答案
您是否正在向数据绑定List< CustomClass>中添加项目?在后台线程上?然后,您可以使用调度程序来编组Add调用以返回UI线程:
Are you adding items to the data bound List<CustomClass> on a background thread? Then you could use the dispatcher to marshall the Add call to back the UI thread:
Application.Current.Dispatcher.BeginInvoke(new Action(()=> { yourCollection.Add(yourItem); })));
对所有修改源集合的添加和删除操作执行此操作。
Do this for all Add and Remove operations that modify the source collection.
您还应该替换List< CustomClass>带有ObservableCollection<>如果您希望DataGrid在项添加到源集合时自动更新。 ObservableCollection提供更改通知,但列表不提供: http://msdn.microsoft.com/en-us/library/ms668604%28v=vs.110%29.aspx 。
You should also replace the List<CustomClass> with an ObservableCollection<> if you want the DataGrid to get updated automatically as items are added to the source collection. An ObservableCollection provides change notifications but a List doesn't: http://msdn.microsoft.com/en-us/library/ms668604%28v=vs.110%29.aspx.
也确保将项目添加到源集合中,而不是添加到DataGrid控件的Items属性中。
Also make sure that you are adding items to the source collection rather than to the Items property of the DataGrid control.
这篇关于将项目添加到List< CustomClass>这是DataBinded到DataGrid的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!