我有一個WPF應用程序有一個列表框綁定到一個ObservableCollection從數據庫中檢索它的數據。我試圖通過使用DispatcherTimer每分鐘刷新ListBox數據。ListBox ObservableCollection重複
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
然後,我有我的兩個類的集合,如下所示(我很新的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結果。如何刷新列表框只有來自表中的新數據或數據更改?
我真的很努力地找出錯誤的地方,以及需要添加/刪除哪些內容才能正常工作。
如果有任何細節我想念,請讓我知道。
馬特
酷這是一件有(工作,已經成爲在相當不錯轉換C#,只是沒有在寫它的任何好處)。現在,我會將此添加到MeetingList類嗎? – Lima
在'getRoomMeetingDetails'分 – Sascha
偉大的,謝謝你,這使得它更容易。我試試看看它是如何工作的。 – Lima