简体   繁体   English

如何在运行时将行添加到wpf应用程序的datagrid中?

[英]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. 我将值动态添加到与datagrid的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. 从与Dispatcher线程不同的线程对其SourceCollection进行更改。

How to resolve this? 如何解决呢?

Regards, 问候,

Tanya 谭雅

you simply have to add the Item to the Observable Collection. 您只需要将项目添加到Observable集合中。 Your Threading Error seems that you try to add the item in a not ui thread. 您的线程错误似乎是您尝试将项目添加到非ui线程中。 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"}));
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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