获取/设置Visual Basic ObservableCollection属性的其他方法

时间:2016-01-22 08:28:21

标签: wpf vb.net visual-studio observablecollection

我想知道是否有其他方法来设置/获取observableCollection属性的值。请参阅以下示例

我说我有

Public Class Record
     public Property Field1 as string
     public Property Field2 as string
End Class
Public RecordCollection as new ObservableCollection(Of Record)
Public sRecord as Record

Public Sub TestRecord()
    sRecord = new Record
    sRecord.Field1 = "test"
    sRecord.Field2 = "test2"
    RecordCollection.add(sRecord)

    listview1.ItemsSource = RecordCollection

End Sub

我的问题是如何设置或获取以下示例中的记录属性?

Public Sub TestRecord()
    sRecord = new Record
    sRecord("Field1") = "test"
    sRecord("Field2") = "test2"
End Sub

或者还有其他方法吗?

2 个答案:

答案 0 :(得分:1)

此处为您的案例使用System.Reflection的示例

测试类

Public Class Record
   Public Property Field1 As String
   Public Property Field2 As String
End Class

实施例

Dim data As New DataTable()
data.Columns.Add("Field1", GetType(String))
data.Columns.Add("Field2", GetType(String))

Dim dr As DataRow
dr = data.NewRow()
dr.SetField("Field1", "0")
dr.SetField("Field2", "Zero")
data.Rows.Add(dr)

dr = data.NewRow()
dr.SetField("Field1", "1")
dr.SetField("Field2", "One")
data.Rows.Add(dr)

For Each row As DataRow In data.Rows
    Dim temp As New Record()
    For Each prop As PropertyInfo In GetType(Record).GetProperties()
        If data.Columns.Contains(prop.Name) = True Then
           prop.SetValue(temp, row(prop.Name))
        End If
    Next
    Console.WriteLine($"{temp.Field1}, {temp.Field2}")
Next

将在控制台中打印结果:

0, Zero
1, One

但是,请再次考虑使用Entity Framework或其他一些ORM(对象关系映射器)框架。

答案 1 :(得分:1)

您可以使用Record类中的Default Property功能:

Public Class Record
        Private fields As New Dictionary(Of String, String)
        Public Property Field1 As String
            Get
                Return fields("Field1")
            End Get
            Set(value As String)
                fields("Field1") = value
            End Set
        End Property


        Public Property Field2 As String
        'Same code as Field1 but with "Field2" of course

        Default Public Property Item(field As String)
            Get
                Return fields(field)
            End Get
            Set(value)
                fields(field) = value
            End Set
        End Property
End Class

然后可以访问:

   Dim record As New Record
   record("Field1") = "Hello Default Property!"
   record.Field2 = "Hello Field2 !"
   Console.WriteLine(record("Field1"))