You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF DataGridTextColumn双击编辑时如何避免EditItem不允许异常?

解决DataGrid编辑时的"EditItem is not allowed for this view"异常

这个问题的核心原因很明确:你直接通过DG.Items.Add()添加数据时,DataGrid使用的是默认的非可编辑ItemCollection,它不支持EditItem操作,所以双击编辑时就会抛出这个异常。

要解决这个问题,只需要做一个关键调整:用ObservableCollection<T>作为DataGrid的数据源,而不是直接往Items集合里加数据。下面是具体的修改步骤:

1. 改用ObservableCollection作为ItemsSource

修改窗口加载的代码,创建一个ObservableCollection实例并赋值给DataGrid的ItemsSource:

Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
    ' 创建支持编辑和通知的集合
    Dim nameCollection As New ObservableCollection(Of CName)()
    nameCollection.Add(New CName())
    ' 将集合绑定到DataGrid
    Me.DG.ItemsSource = nameCollection
End Sub

2. 确保实体类正确实现INotifyPropertyChanged

虽然你提到已经实现了这个接口,但还是贴一个标准实现供参考(保证双向绑定和属性变化通知正常工作):

Imports System.ComponentModel

Public Class CName
    Implements INotifyPropertyChanged

    Private _name As String = "not editable name"
    Public Property Name As String
        Get
            Return _name
        End Get
        Set(value As String)
            If _name <> value Then
                _name = value
                OnPropertyChanged(NameOf(Name))
            End If
        End Set
    End Property

    ' 实现INotifyPropertyChanged接口的事件
    Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged

    Protected Sub OnPropertyChanged(propertyName As String)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub
End Class

为什么这样能解决问题?

  • ObservableCollection<T>是WPF专门为数据绑定设计的集合类型,它不仅支持自动通知UI数据的增删变化,还实现了IEditableCollectionView接口,这是DataGrid支持编辑操作的必要条件。
  • 直接使用Items.Add()会让DataGrid使用底层的非编辑视图,完全绕过了WPF数据绑定的标准机制,自然无法支持编辑。
  • 正确实现INotifyPropertyChanged能确保当你编辑完单元格内容后,实体类的属性值会同步更新,同时UI也能感知到这些变化。

你的XAML部分(不管是DataGridTextColumn还是DataGridTemplateColumn)都不需要修改,只要完成上面的调整,双击编辑就能正常工作了。

内容的提问来源于stack exchange,提问作者tsolina

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:23:46