WPF: MVVM and editing hierarchical data

I'm still trying to wrap my head around MVVM. Let's say I have a model that looks something like this:

public class Company { public IList<Division> Divisions { get;set;} } public class Division { public string Name { get;set;} public IList<Department> Departments { get;set} } public class Department { public string UnitNumber { get;set;} public string DepartmentName { get;set;} public IList<Employee> Employees { get;set;} } public class Employee { public string FirstName { get;set;} public string LastName { get;set;} public string JobTitle { get;set;} } 

Now let me say that I want to display the hierarchy of companies in a hierarchical grid, I create the CompanyViewModel class below:

 public class CompanyViewModel : INotifyPropertyChanged { private Company _company; public Company Company { get { return _company;} set { _company = value; NotifyPropertyChanged("Company");} } } 

Now, in my view (WPF), I set the data context in the ViewModel, and the selected dataset would snap to the Company path. Everything is wonderful so far ... I get a nice extension / smoothing interface in Divions, departments, employees ...

Besides:

  • What if the grid is editable ... Department names must be changed (and checked by ViewModel, same for Employee names ..

  • What if I want to add new employees, departments, etc., all this should be reflected in the grid without overwriting (what is the WPF data anchor point right?)

Potential solution:

You have a separate ViewModel class for each domain class ...

This, apparently, means a lot from displaying DTO β†’ ViewModel, duplication (because they are almost the same objects and yet not quite.) Given that I'm probably already mapped to some kind of ORM β†’ DTO on object the service side, sending it through the wiring (WCF) to the client, matching each DTO hierarchy into its own ViewModel is a difficult and expensive process (not to mention the work associated with this).

Bleeding such as INotifyPropertyChanged, ObservableCollection, etc. in my DTO seem to be hacked.

Does anyone have a better solution? I'm crazy?; -)

+4
source share
2 answers

"Bleeding such as INotifyPropertyChanged, ObservableCollection, etc. in my DTOs seem to be a hack."

I feel your pain, but this is the approach I have taken on several projects.

Bottom line: in order to bind WPF data to β€œwork”, as advertised objects / collections that you bind, you need to support INotifyPropertyChanged and ObservableCollection.

Personally, I think that creating a DTO that supports this is a lot less work than constantly moving the data back and forth to a viewmodel or other intermediate object, which is essentially a richer version of the DTO object.

+3
source

If you don't like entering code for INotifyPropertyChanged, and you also use automatic properties, why not take a look at MoXAML Power Toys , which allows you to convert automatic properties to recognizable?

+1
source

All Articles