Can I have multiple ViewModel for a View in WPF

1.6k Views Asked by At

Can I have multiple ViewModel for a View in WPF? Because some times we need to show the view only in simple view format and sometimes the same view has to shown in editable format. Hence we can create seperate view models for each.

So is there any way to hook 2 diffrent view models to a view?

2

There are 2 best solutions below

3
On

A ViewModel should serve as the Data Context for your View, so that would only allow a single VM.

There is no reason why you could not break you View up in to multiple UserControls, each with their own ViewModel.

0
On

Generally you're going to bind your View to a single type of View Model. That's not to say that your type couldn't be an interface, or a base class from which both of your views inherit.

I tend to only use an interface or base/derived class situation when I have a single view model type that is going to span several different views. For example if I have two different types of forms that display widget information, I would create a single base Widget ViewModel class.

In your case, it sounds you should either a.) create two views for your simple and advanced views or b.) simply use a single ViewModel class.