Viewmodel has lots of properties which bind to view [closed]

Iron just a moment. 1 answers, 0 views
c# wpf

I created a configuration View. so it binds a lot of properties in Viewmodel. But I have a another class People and I want to assign properties of viewmodel to class People.

class Viewmodel 
{
   public string name {get;set;}
   public int age {get;set;}
   public string nationality {get;set;}
   public string hobby {get;set;}
   ………… 

}

class People
{
   public string name {get;set;}
   public int age {get;set;}
   public string nationality {get;set;}
   public string hobby {get;set;}
   public People[] friends {get;set;}
   ………… 
   public void AddFriend(People people)
   {
    //add friend to this
   }
}

I have to write a function:

void Assign()
{ 
  People.name = Viewmodel.name;
  People.age= Viewmodel.age;
  …………
}

How could I refactor this function? I usually will define more than 10 properties in viewmodel.

1 Answers


akjoshi 05/23/2017.

This is a very common problem while working with MVVM. I believe the best solution to resolve this is to implement INotifyPropertyChanged in Models; that way you can directly bind the model properties in view and there will be no need to update them explicitly.

Even MS prescribes doing that -

Typically, the model implements the facilities that make it easy to bind to the view. This usually means it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection class, which provides an implementation of the INotifyCollectionChanged interface.

Taken from - http://msdn.microsoft.com/en-us/library/gg405484(PandP.40).aspx

Although its up to you to decide whether you want that type of implementation or not; and sometimes its not possible to do this too (e.g. you don't have ownership of model classes).

In case you have doubts about implementing INotifyCollectionChanged in Models, have a look at following SO question -

https://stackoverflow.com/questions/6922130/in-mvvm-model-should-the-model-implement-inotifypropertychanged-interface

Language

Popular Tags