ListBox ObservableCollection重复

时间:2011-08-18 11:25:38

标签: wpf vb.net .net-3.5 observablecollection

我有一个WPF应用程序,它有一个绑定到ObservableCollection的列表框,它从数据库中检索它的数据。我试图通过使用DispatcherTimer每分钟刷新一次ListBox数据。

Dim dispatcherTimer As DispatcherTimer = New System.Windows.Threading.DispatcherTimer
AddHandler dispatcherTimer.Tick, AddressOf getRoomMeetingDetails
dispatcherTimer.Interval = New TimeSpan(0, 2, 0)
dispatcherTimer.Start()

调用getRoomMeetingDetails方法如下。

Public Sub getRoomMeetingDetails()
  If Not My.Settings.rbConn = Nothing And _
     Not gl_rmName = Nothing Then
       Dim sqlConn As New SqlConnection(My.Settings.rbConn)
       Dim sqlquery As String = "SELECT  *" & _
                                        "FROM table " & _
       Dim sqlCmd As New SqlCommand(sqlquery, sqlConn)
       sqlConn.Open()
       Dim dr As SqlDataReader
       dr = sqlCmd.ExecuteReader
       While dr.Read
         roomMeetingList.Add(New meetingDetails() With {.eMeetingId = dr.Item("dId")})
       End While
  End If
End Sub

然后我将我的两个类用于Collection(我是ObservableCollections的新手,并且我已经尽力在MSDN示例中建模我的代码,所以如果这不是用来实现我的最佳方法我想要实现,或者可以更轻松,请让我知道)

Public Class MeetingList
  Inherits ObservableCollection(Of meetingDetails)
  Private Shared list As New MeetingList

  Public Shared Function getList() As MeetingList
    Return list
  End Function

  Private Sub New()
    AddItems()
  End Sub

  Public Shared Sub reset(ByVal rmName As String)
    list.ClearItems()
    list.AddItems()
  End Sub

  Private Sub AddItems()
  End Sub
End Class

Public Class meetingDetails
  Implements INotifyPropertyChanged

  Public Sub New()
  End Sub
  Public Property eID() As String
    Get
      Return _eID
    End Get
    Set(ByVal value As String)
       _eID = value
       OnPropertyChanged("eID")
    End Set
  End Property
  Private _eID As String

  Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged
End Class

当发生每分钟调用DispatcherTimer时,ListBox数据是重复的,我相信是因为getRoomMeetingDetails方法在每个tick上添加所有SQL结果。如何仅使用表中的新数据或数据更改来刷新ListBox?

我真的很难找到我出错的地方以及需要添加/删除的内容才能实现。

如果有任何我遗漏的细节,请告诉我。

马特

1 个答案:

答案 0 :(得分:1)

要么在再次添加之前清除列表框中的所有数据,要么检查集合。我假设您的eID是主键?做这样的事情:

if ( roomMeetingList.Where ( entry => entry.eID == dbID ).Count () == 0 ) {
    // add
}

C#代码,但它显示了这个想法

developerFusion的转换成了这个VB:

If roomMeetingList.Where(Function(entry) entry.eID = dbID).Count() = 0 Then
     ' Add
End If