Brunov's blog

Sergey Vyacheslavovich Brunov's blog

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.

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