【发布时间】:2023-03-15 19:21:01
【问题描述】:
我在 WPF 应用程序中有一个列表框,它显示照片对象的可观察集合。当照片被添加到集合中时,UI 需要立即显示新图像。我知道这可以使用 CollectionChanged 事件来处理。我四处寻找有关如何使用句柄集合更改事件的示例,但我没有找到任何有效的方法。有谁知道有什么好的例子吗?
另一件事是图像来自我计算机上的一个目录,我有一个文件系统观察程序监视该目录是否有添加或删除的新照片。我目前正在使用文件系统事件处理程序在添加或删除照片时更新集合,但问题是当我将新照片添加到目录时,抛出异常说我无法从不是线程的线程修改集合主线程。有谁也知道如何解决这个问题?下面是这个问题的代码:
public class PhotoList : ObservableCollection<Photo>
{
DirectoryInfo _directory;
private FileSystemWatcher _watcher;
public PhotoList()
{
_watcher = new FileSystemWatcher();
MessageBox.Show("Watching..");
_watcher.Filter = "*.jpg";
_watcher.Path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
_watcher.EnableRaisingEvents = true;
_watcher.Created += new FileSystemEventHandler(FileSystemWatcher_Created);
_directory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
}
public void Update()
{
foreach(FileInfo f in _directory.GetFiles("*.jpg"))
{
Add(new Photo(f.FullName));
}
}
public string Path
{
set
{
_directory = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
Update();
}
get
{
return _directory.FullName;
}
}
public void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
Add(new Photo(e.FullPath));
}
}
【问题讨论】:
标签: c# wpf observablecollection inotifycollectionchanged