2010-12-23 78 views
1

我在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)); 
    } 
} 

回答

0

在Dispatcher.Invoke()中包装Add(新照片(e.FullPath))。这样Add就会在UI线程上调用

相关问题