WPF 数据网格“此视图不允许编辑项"例外 [英] WPF datagrid "EditItem is not allowed for this view" 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);
当我添加项目时:
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
设置为集合.DataGrid 将从实现 IEditableCollectionView
接口的 itemsource 中生成视图以允许编辑.这个接口有函数 EditItems()
可以让编辑发生.
You should not update the Items directly of your DataGrid
but rather set the ItemsSource
to the collection. DataGrid will generate the view out of the itemsource that implements IEditableCollectionView
interface in order to allow the editing. This interface has function EditItems()
which let the editing happen.
所以为了解决这个问题.在您的虚拟机/代码后面创建 ObservableCollection
属性,并将 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;
在你的构造函数中,你可以通过更新来初始化这个集合.每当您想在 DataGrid
中添加项目时,只需将项目添加到 Observable 集合 (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.
这篇关于WPF 数据网格“此视图不允许编辑项"例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!