Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
278 views
in Technique[技术] by (71.8m points)

c# - Adding an item to a List<CustomClass> which is DataBinded to a DataGrid

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

Also make sure that you are adding items to the source collection rather than to the Items property of the DataGrid control.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...