c# - WPF 数据网格 "EditItem is not allowed for this view"异常

标签 c# .net 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);

当我添加项目时:

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

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

"EditItem" is not allowed for this view.

如何让那个错误不弹出?

最佳答案

不应直接更新 DataGrid 的 Items,而应将 ItemsSource 设置为集合。 DataGrid 将从实现 IEditableCollectionView 接口(interface)的 itemsource 中生成 View 以允许编辑。此接口(interface)具有函数 EditItems(),可让编辑发生。

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

ObservableCollection<Type> MyCollection{get;set;}


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

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

关于c# - WPF 数据网格 "EditItem is not allowed for this view"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19334326/

相关文章:

wpf - 如何连接 ViewModel 中的撤消命令以供 Ctrl-Z 调用?

c# - 使用 Telerik 组件正确部署应用程序

c# - 在 WPF 的只读文本框中启用复制粘贴功能

C# WPF 在不知道列的情况下将数据网格列大小设置为自动

c# - 检查两个键是否匹配无法正常工作

c# - DateTime.ToString ("yyyy.MM.dd-HH_mm_ss") 仅在某些日本笔记本电脑上导致错误的 'year' 组件

c# - “80040154 类未注册”与 ASP.NET 的互操作

c# - 在 Windows 窗体中为禁用的控件注册 MouseEnter/MouseLeave 事件?

javascript - 发布JSON数据时MVC Controller 的string[]参数为null

.net - 当接口(interface) ReadOnly 属性在 C#.NET 中有效时,为什么不能在 VB.NET 中覆盖它?