WPF datagrid“此视图不允许使用EditItem”exception

我以编程方式添加DataGrid

 System.Windows.Controls.DataGrid dataGrid = new System.Windows.Controls.DataGrid(); dataGrid.GridLinesVisibility = DataGridGridLinesVisibility.None; dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden; dataGrid.Background = Brushes.White; DataGridTextColumn textColumn = new DataGridTextColumn(); textColumn.Width = 250; textColumn.Header = "Account"; textColumn.Binding = new Binding("Account"); dataGrid.Columns.Add(textColumn); 

当我添加Item时:

Globals_Liker.list_datagrid [tabControl1.SelectedIndex] .Items.Add(Globals_Liker.list_item [tabControl1.SelectedIndex] [I]);

但如果我双击项目我有错误:

此视图不允许使用“EditItem”。

如何使该错误不会弹出?

should not update the Items directly of your DataGridshould not update the Items directly of your DataGrid ItemsSource设置为集合。 DataGrid将生成实现IEditableCollectionView接口的itemsource的视图,以便进行编辑。 该接口具有EditItems()函数,可以进行编辑。

所以为了解决这个问题。 在VM / Code后面创建ObservableCollection属性,并将DataGrid ItemsSource设置为它

 ObservableCollection MyCollection{get;set;} Globals_Liker.list_datagrid[tabControl1.SelectedIndex].ItemsSource = MyCollection; 

在构造函数中,您可以通过新建它来初始化此集合。 每当你想在DataGrid添加项目时,只需在Observable集合(MyCollection)中添加项目,它就会显示在网格上并且可以编辑。