我有一个 ObservableCollection,它使用 FileSystemWatcher 自动添加已添加到目录中的其他 PNG 图像。ListBox 使用以下 XAML 将 ItemsSource 数据绑定到 Photos 对象。
<ListBox ItemsSource="{Binding Source={StaticResource Photos}}" IsSynchronizedWithCurrentItem="True"/>
但是,当 PNG 文件添加到受监视的目录时,将调用 OnPhotoCreated 事件(断点确认这一点),但 ListBox UI 并未更新。有任何想法吗?
Public Class Photos
Inherits Collections.ObjectModel.ObservableCollection(Of BitmapImage)
' Events
Public Event ItemsUpdated As EventHandler
' Fields
Private FileSystemWatchers As Dictionary(Of String, FileSystemWatcher) = New Dictionary(Of String, FileSystemWatcher)
' Methods
Protected Overrides Sub ClearItems()
MyBase.ClearItems()
Me.FileSystemWatchers.Clear()
End Sub
Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As BitmapImage)
MyBase.InsertItem(index, item)
Dim ImagePath As String = IO.Path.GetDirectoryName(item.UriSource.LocalPath)
If Not Me.FileSystemWatchers.ContainsKey(ImagePath) Then
Dim FileWatcher As New FileSystemWatcher(ImagePath, "*.png")
FileWatcher.EnableRaisingEvents = True
AddHandler FileWatcher.Created, New FileSystemEventHandler(AddressOf Me.OnPhotoCreated)
AddHandler FileWatcher.Deleted, New FileSystemEventHandler(AddressOf Me.OnPhotoDeleted)
AddHandler FileWatcher.Renamed, New RenamedEventHandler(AddressOf Me.OnPhotoRenamed)
Me.FileSystemWatchers.Add(ImagePath, FileWatcher)
End If
End Sub
Private Sub OnPhotoCreated(ByVal sender As Object, ByVal e As FileSystemEventArgs)
MyBase.Items.Add(New BitmapImage(New Uri(e.FullPath)))
RaiseEvent ItemsUpdated(Me, New EventArgs)
End Sub
Private Sub OnPhotoDeleted(ByVal sender As Object, ByVal e As FileSystemEventArgs)
Dim index As Integer = -1
Dim i As Integer
For i = 0 To MyBase.Items.Count - 1
If (MyBase.Items.Item(i).UriSource.AbsolutePath = e.FullPath) Then
index = i
Exit For
End If
Next i
If (index >= 0) Then
MyBase.Items.RemoveAt(index)
End If
RaiseEvent ItemsUpdated(Me, New EventArgs)
End Sub
Private Sub OnPhotoRenamed(ByVal sender As Object, ByVal e As RenamedEventArgs)
Dim index As Integer = -1
Dim i As Integer
For i = 0 To MyBase.Items.Count - 1
If (MyBase.Items.Item(i).UriSource.AbsolutePath = e.OldFullPath) Then
index = i
Exit For
End If
Next i
If (index >= 0) Then
MyBase.Items.Item(index) = New BitmapImage(New Uri(e.FullPath))
End If
RaiseEvent ItemsUpdated(Me, New EventArgs)
End Sub
End Class
更新 #1: 我尝试了一个事件,如下所示。这会导致 InvalidOperationException 崩溃,“调用线程无法访问此对象,因为不同的线程拥有它”当新图像试图滚动到视图中时。我希望不需要 Refresh 方法。
Dim Photos As Photos = CType(Me.FindResource("Photos"), Photos)
AddHandler Photos.ItemsUpdated, AddressOf Me.Photos_ItemsUpdated
Private Sub RefreshPhotos()
'
If Me.ImageListBox.Dispatcher.CheckAccess = True Then
Me.ImageListBox.Items.Refresh()
Else
Dispatcher.BeginInvoke(DispatcherPriority.Normal, New DispatcherMethodCallback(AddressOf Me.RefreshPhotos))
End If
'
End Sub
Private Sub Photos_ItemsUpdated(ByVal sender As Object, ByVal e As EventArgs)
'
Debug.WriteLine("PhotosUpdated")
Me.RefreshPhotos()
'
End Sub