Andahari Andahari - 2 months ago 17x
C# Question

How to implement MVVM with the WPF treeview?

I haven't worked with WPF or the MVVM pattern before.

However I want to create a simple document management system and would like to do so using the aforementioned technologies.

I've modeled a hierarchical file system in my Database and want to display it in a treeview.


As you can see each directory can have multiple sub-directories and multiple files in it.

I've read some tutorials on the topic and if I understood them correctly then I should create model classes for directory and file in which the data from the database is stored directly.


public class Directory
private int id;
public int Id
get { return id; }
set { id = value; }

private string name;
public string Name
get { return name; }
set { name = value; }

private int parent;
public int Parent
get { return parent; }
set { parent = value; }

private DateTime dateCreatedOn;
public DateTime DateCreatedOn
get { return dateCreatedOn; }
set { dateCreatedOn = value; }

Then each model class should have an associated view-model class which implements additional properties which are only relevant for describing the UI element to which objects of this class will be bound.

In this case the view-model class should have the isExpanded and isSelected Property of the treeviewitem.

Then I would need another view-model class for the entire treeview which would contain the collection of directorys and files which should be displayed.

My questions are:

  1. Have I understood the mvvm concept correctly?

  2. Which class, the model or the view-model, of directory should implement the iNotifyPropertyChanged interface?

  3. Should the view-model class of directory contain the same properties as the model class or is a reference to a model-object in the view-model class sufficient?

  4. If the view-model class should contain the same properties of the model class again, then whats the best way to make sure that model-objects and the associated view-model objects always stay synchronized?

I hope this question is understandable and thanks for all help.


answer 1) yes.

answer 2) view-model should have the iNotifyPropertyChanged.

answer 3) yes. and they should be explicitly mapped. i.e.:

   this.property1 = model.property1

answer 4) use the same names, and see answer 3.

If you use a private-public property pair in the view-model, use iNotifyPropertyChanged in the view-Model, and map the properties of the model to the corresponding properties in the view-model, you should be set.