I have listbox in a WPF application that displays an observable collection of photo objects. When a photo is added to the collection the UI needs show the new image right away. I understand this can be handled using the CollectionChanged event. I have looked around for examples on how to use the handle collection changed events but I havent found anything that worked. Does anyone know of any good examples?
Another thing is that the images are coming from a directory on my computer and i have a file system watcher watching the directory for new photos being added or deleted. I am currently using file system event handler to update the collections when a photo is added or deleted but the problem is when i add a new photo to the directory, an exception is thrown saying that I cant modify the collection from a thread thats not the main thread. Does anyone know how to solve this problem too? Here is the code for this problem:
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));
}
}
First question: ObservableCollection<T>
already implements INotifyCollectionChanged
, so simply bind on that object and you are fine, the UI will get the updates happening in the collection automatically.
Second question: See this post: WPF threading: can I update a control's data context in a non-UI thread? and the accompening comments.