以编程方式将项添加到datagrid

时间:2017-06-21 07:26:57

标签: wpf vb.net

我在WPF / VB.NET中添加了一个数据网格,设法在代码中创建列但我无法弄清楚如何向datagrid添加行。

 Private Sub button_Click(sender As Object, e As RoutedEventArgs) Handles button.Click
    Dim c1 As New DataGridTextColumn()
    c1.Header = "Šifra"
    c1.Width = 100
    c1.Binding = New Binding("Šifra")
    gridRacun.Columns.Add(c1)

    Dim c2 As New DataGridTextColumn()
    c2.Header = "Naziv artikla"
    c2.Width = 500
    c2.Binding = New Binding("Naziv artikla")
    gridRacun.Columns.Add(c2)

    Dim c3 As New DataGridTextColumn()
    c3.Header = "Količina"
    c3.Width = 100
    c3.Binding = New Binding("Količina")
    gridRacun.Columns.Add(c3)

    Dim c4 As New DataGridTextColumn()
    c4.Header = "Cijena"
    c4.Width = 100
    c4.Binding = New Binding("Cijena")
    gridRacun.Columns.Add(c4)


End Sub

如何为每个列的datagrid添加字符串,字符串是4个标签的内容,这些标签将更改,按钮点击我希望将label1.content设置为column1,lebel2.content设置为column2等?

1 个答案:

答案 0 :(得分:1)

您可以通过创建一个包含项目值的类来向DataGrid添加自定义项目:

Class Item
    Private _name As String

    Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            Me._name = value
        End Set
    End Property
    //Some other properties
End Class

现在您可以像这样创建DataGrid列:

Dim myColumn As New DataGridTextColumn()

myColumn.Header = "Name"
myColumn.Binding = New Binding("Name")

dataGrid.Columns.Add(myColumn)

现在可以通过向DataGrid添加项来添加行:

Dim item = New Item With {.Name = "Terry Adams"}
dataGrid.Items.Add(item)

我希望这会有所帮助。