简体   繁体   中英

How to add the row to a datagrid in wpf application at runtime?

I have got an error when i dynamically add values to the observable collection which is binded with the datagrid's ItemSource.

 _Items.Add(new GridViewItem() {Name="Test1",ID=1});
 Error:This type of CollectionView does not support 

changes to its SourceCollection from a thread different from the Dispatcher thread.

How to resolve this?

Regards,

Tanya

you simply have to add the Item to the Observable Collection. Your Threading Error seems that you try to add the item in a not ui thread. so you have to use a dispatcher

  public ObsrevableCollection<MyTestItem> MyCollection {get; set;}


  <DatagGrid ItemsSource="{Binding MyCollection}" />


  public void Add()//is called from a not ui thread
  {
      Application.Current.Dispatcher.BeginInvoke((Action)(()=>this.MyCollection.Add(new MyTestItem(){ID=1, Name="Test1"}));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM