如何在数据网格中显示列表值?

时间:2015-03-10 08:31:37

标签: wpf vb.net wpfdatagrid

这可能是一个新手问题。

我想在DataGrid中显示一些信息。这不一定是双向绑定,我只需要将DataGrid显示为输出。信息存储在由List项组成的List(Of String)中。 List(Of String)项是整行,其中该列表中的每个String项都会进入DataGrid中自己的列。

那么最简单的方法是什么?

我试着这样做:
创建了DataGrid

    <DataGrid x:Name="MyDataGrid" AutoGenerateColumns="True" ItemsSource="{Binding}" Margin="24,17,144,37">
    </DataGrid>

通过向第一个列表添加一些数据来创建“行”条目:

    Dim MyEntryList As New List(Of String)

    MyEntryList.Add("SomeName")
    MyEntryList.Add("SomeInfo")
    MyEntryList.Add("SomeStuff")

将创建的“行”列表添加到包含列表中:

    Dim MyDataList As New List(Of List(Of String))

    MyDataList.Add(MyEntryList)

最后尝试设置DataGrid的来源:

    Me.MyDataGrid.ItemsSource = MyDataList

DataGrid显示了一些描述容量和计数的数字,而不是那些字符串: enter image description here

如何让它显示列表的内容?

1 个答案:

答案 0 :(得分:0)

您应该尝试构建一些对象或Datatable来填充Datagrid。请参阅以下代码

 <DataGrid x:Name="MyDataGrid" AutoGenerateColumns="True" >
    </DataGrid>

Imports System.Collections.ObjectModel
        Class MainWindow

        Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)

            Dim lst As New ObservableCollection(Of SomeObject)
            For index = 1 To 10
                Dim obj As New SomeObject
                obj.SomeName = "test" + index.ToString
                obj.SomeInfo = "info" + index.ToString
                lst.Add(obj)
            Next
            MyDataGrid.ItemsSource = lst
        End Sub
    End Class

    Class SomeObject
        Private name As String
        Public Property SomeName() As String
            Get
                Return name
            End Get
            Set(ByVal value As String)
                name = value
            End Set
        End Property
        Private info As String
        Public Property SomeInfo() As String
            Get
                Return info
            End Get
            Set(ByVal value As String)
                info = value
            End Set
        End Property

    End Class