Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to create a ViewModel in MVVM

Assume I have a class called Customer. Now I need to render the customer on view. So I created CustomerViewModel to use in binding. I am looking for the best way to create the CustomerViewModel class. Following are my thoughts on creating it.

1 - Create all the properties in the customer again on the view model. Inject the customer instance into view model and each properties will retrun the value from this customer object. Advantage of this method is that I can create a common base class for all view models and have common functionality dumped there. Disadvantage will be the time required to create all the properties again on the view model and doing the maintenance.

2 - Derive the view model from customer. So I have all the propeties of customer in view model. But this will not allow me to use a common base class and put common view model logic there.

So I am wondering what will be the best method to create a view model? Is there any alternative methods that are better than what I thought?

like image 261
Navaneeth K N Avatar asked Dec 22 '09 06:12

Navaneeth K N


People also ask

What logic should be in ViewModel?

ViewModel: ViewModel is the middle layer between the view and model. ViewModel contains the business logic, which manipulates the row data to show in the view. Any kind of function and methods should be in the view model. The iNotifyPropertyChanged interface is used in the ViewModel to achieve two-way binding.

What is the use of ViewModel in MVVM?

The purpose of ViewModel is to encapsulate the data for a UI controller to let the data survive configuration changes. For information about how to load, persist, and manage data across configuration changes, see Saving UI States.

Should a ViewModel have a constructor?

At present, this means that every ViewModel must have a public constructor which has either no parameters or which has only string parameters. So the reason your ViewModel isn't loading is because the MvxDefaultViewModelLocator can't find a suitable constructor for your ViewModel.


1 Answers

You should consider reading Josh Smith's article on MVVM.

He also have a framework called MVVM Foundation that has a ViewModel base class. In general I think that the way he implements ViewModel's is the best overall.

like image 115
Chris Nicol Avatar answered Oct 07 '22 07:10

Chris Nicol