我正在尝试创建一个由 DataGrid 和几个按钮组成的 UserControl。按钮将处理添加/删除行(需要是按钮)。DataGrid 绑定到自定义的可观察集合。集合属性会有所不同(所以我会自动生成列)。
如何添加新行?通常我只会修改可观察的集合。我尝试将新行直接添加到控件中:
dgMain.Items.Add(New DataGridRow())
但我得到一个对我来说意义不大的错误:
使用 ItemsSource 时操作无效。改为使用 ItemsControl.ItemsSource 访问和修改元素。
这是后面的当前代码:
Public Class DataGrid
Sub New()
InitializeComponent()
End Sub
#Region "Dependency Properties"
Public Shared MyItemsSourceProperty As DependencyProperty = DependencyProperty.Register("MyItemsSource", GetType(IEnumerable), GetType(DataGrid))
Public Property MyItemsSource() As IEnumerable
Get
Return DirectCast(GetValue(MyItemsSourceProperty), IEnumerable)
End Get
Set(value As IEnumerable)
SetValue(MyItemsSourceProperty, value)
End Set
End Property
#End Region
#Region "Buttons"
Private Sub btnAdd_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles btnAdd.Click
dgMain.Items.Add(New DataGridRow())
End Sub
#End Region
End Class
那么有人知道我如何添加新行吗?
谢谢你的帮助。
编辑:这是创建数据的方式:
Dim np As New ObPerson
np.Add(New Person With {.FirstName = "Jane", .LastName = "Mitel", .Age = 18})
np.Add(New Person With {.FirstName = "Joe", .LastName = "Bloggs", .Age = 92})
UserControlInstance.MyItemsSource = np
Public Class ObPerson
Inherits ObservableCollection(Of Person)
End Class
EDIT2:接受答案的VB版本:
Public Shared Sub AddNewElement(l As IList)
If l Is Nothing OrElse l.Count = 0 Then
Throw New ArgumentNullException()
End If
Dim obj As Object = Activator.CreateInstance(l(0).[GetType]())
l.Add(obj)
End Sub
Usage: AddNewElement(MyItemsSource)