WPF数据网格" EditItem不允许这种观点"例外不允许、网格、观点、数据

2023-09-03 06:55:55 作者:山茶酒与雾

我编程方式添加的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);

当我添加项:

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

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

但是,如果我双击上的项目我有错误:

But if I doubleclick on Items I have error:

EditItem不允许这种观点。

"EditItem" is not allowed for this view.

如何让这个错误不会弹出?

How to make that error does not pop up?

推荐答案

不应该更新您的DataGrid 直接的项目,而是设定的ItemsSource 的集合,它实现 IEditableCollectionView 接口,以便让编辑。这个接口有功能 EditItems()这让编辑发生。

You should not update the Items directly of your DataGrid but rather set the ItemsSource to the collection that implements IEditableCollectionView interface in order to allow the editing. This interface has function EditItems() which let the editing happen.

因此​​,为了解决这个问题。创建的ObservableCollection 属性在你的虚拟机/ code后面,设置DataGrid的ItemsSource它像

So in order solve this problem. Create the ObservableCollection property in your VM/Code behind and set the DataGrid ItemsSource to it like

ObservableCollection<Type> MyCollection{get;set;}


Globals_Liker.list_datagrid[tabControl1.SelectedIndex].ItemsSource = MyCollection;

在你的构造可以通过newing它初始化此集合。每当你想在你的的DataGrid 添加项目,只需添加在观察的集合(myCollection)将这一项目时,它会显示在网格,可以编辑。

In your constructor you can initialize this collection by newing it. And whenever you want to add item in your DataGrid, just add the item in the Observable collection (MyCollection), it will be shown on grid and will be editable.

 
精彩推荐
图片推荐