我在WPF應用程序中顯示了可觀察的照片對象集合的列表框。當照片被添加到集合中時,UI需要立即顯示新的圖像。我明白這可以使用CollectionChanged事件來處理。我已經四處尋找有關如何使用處理集合更改事件的示例,但我沒有找到任何有效的工具。有誰知道任何好的例子?Observable Collection上收集已更改事件的示例
另一件事是,圖像來自我的電腦上的一個目錄,我有一個文件系統觀察者看着添加或刪除新照片的目錄。我目前正在使用文件系統事件處理程序更新添加或刪除照片時的集合,但問題是當我添加一個新的照片到目錄,引發異常,說我不能修改集合從一個線程那不是主線程。有誰知道如何解決這個問題呢?以下是此問題的代碼:
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));
}
}
非常感謝! – MBU 2010-12-23 02:57:54