ObservableKeyedCollection class
2011-08-04 13:40:10 Moscow time
I am writing a file management application at the moment and I have the following ViewModel
in the application:
public class DirectoryViewModel : ViewModelBase
{
public SomeBindableDictionary<string, DirectoryViewModel> Directories
{
get;
private set;
}
/// <summary>
/// Unique name of directory.
/// </summary>
public string Name
{
get;
private set;
}
// Skipped...
}
So, when a directory is removed from a physical file system, the Directories
dictionary is used to perform remove the corresponding directory ViewModel
by the directory name (directory name is used as an index).
Have found two collection classes that solve the problem.
- ObservableDictionary. The class represents keys and values as separate entities. It isn't so convenient to bind to Key and Value property in HierarchicalDataTemplate. Furthermore, Items and Values collections properties do not implement INotifyCollectionChanged interface.
- ObservableKeyedCollection. The class uses the key which is a part (!) of the values you'd like to store in the collection. The collection does not separate key and value. You need just to bind to the collection as you did it before with
ObservableCollection<T>
class. So, this option suits the requirements very well.
Directories = new ObservableKeyedCollection<string, DirectoryViewModel>(directory => directory.Name);
Directories.AddRange(childDirectories);
The piece of code is quite self-descriptive: it creates an observable keyed collection for directories, directory name is used as a key.
To remove the directory by its name you just need to call:
Directories.Remove("Some directory");
The collection change will be automatically reflected on the UI.
Download.
P.S. After downloading please rename .doc to .zip.
Tags: data binding dictionary keyedcollection mvvm observablekeyedcollection treeview wpf