ObservableCollection中的WPF唯一条目

时间:2011-05-13 20:44:04

标签: wpf vb.net observablecollection

我有一个类客户的ObservableCollection,我从数据库查询中填写。由于表格的连接方式,我有时会在数据中显示两次条目(比尔的邮寄地址与邮寄地址不同)。 每个客户行都有一个ID作为唯一主键,当有人从绑定的ListView中选择一行时,这就是我用来提取更多客户信息的方法。 在这个程序的WinForms版本中,我会在ListView中搜索CustomerID,如果找到它,我会避免第二次插入它。

ObservableCollection似乎没有能力轻易告诉我,如果CustomerID已经存在于该集合的一个类实例中,那么我想知道处理这个问题的最佳方法是什么。

到目前为止我的想法:

' Not sure how to make this work, since the CustomerID and Name would be the same, but the city, state, zip might not be.'
t = new classCustomer(CustomerID, CustomerName, City, State, Zip)
if not sr.contains(t) then
  sr.Add(t)
end if

Possibly figure out how to create an ObservableDictionary, but so far all the examples are in C#, and it may take me a while to port it over to VB.net

有人知道更好的实施吗?

1 个答案:

答案 0 :(得分:3)

你只需要告诉.NET什么定义了一个人,在这种情况下是ID。

只需在客户对象上覆盖Equals,然后您的收藏就能知道2个客户是否相同:

Public Class Person

    Private id As Integer

    Public Sub New(ByVal id As Integer)
        Me.id = id
    End Sub

    Public Overrides Function Equals(ByVal obj As Object) As Boolean

        Return (TypeOf (obj) Is Person) And (DirectCast(obj, Person)).id = Me.id

    End Function

    Public Overrides Function GetHashCode() As Integer
        Return Me.id.GetHashCode()
    End Function

End Class




 Sub Main()

        Dim observable As New ObservableCollection(Of Person)()

        observable.Add(New Person(1))

        Dim duplicate As New Person(1)

        If Not observable.Contains(duplicate) Then
            observable.Add(duplicate) ' never gets hit because of .Equals override
        End If

    End Sub

没有覆盖它不知道如何判断它们是否相同。