WPF datagrid"此视图不允许使用EditItem"异常

prm*_*prm 3 .net c# wpf datagrid

我以编程方式添加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);
Run Code Online (Sandbox Code Playgroud)

当我添加项目时:

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

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

此视图不允许使用"EditItem".

如何使该错误不会弹出?

Nit*_*tin 8

should not update the Items directly of your DataGrid而是设置ItemsSource为集合.DataGrid将从实现IEditableCollectionView接口的itemsource生成视图,以允许编辑.该界面具有EditItems()允许编辑发生的功能.

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

ObservableCollection<Type> MyCollection{get;set;}


Globals_Liker.list_datagrid[tabControl1.SelectedIndex].ItemsSource = MyCollection;
Run Code Online (Sandbox Code Playgroud)

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