I have a window made up of several user controls and was wondering whether each user control have its own view model or should the window as a whole have only one view model?
6 Answers
Absolutely, positively
NO
Your UserControls should NOT have ViewModels designed specifically for them. This is, in fact, a code smell. It doesn't break your application immediately, but it will cause you pain as you work with it.
A UserControl is simply an easy way to create a Control using composition. UserControls are still Controls, and therefore should solely be concerned with matters of UI.
When you create a ViewModel for your UserControl, you are either placing business or UI logic there. It is incorrect to use ViewModels to contain UI logic, so if that is your goal, ditch your VM and place the code in that control's codebehind. If you're placing business logic in the UserControl, most likely you are using it to segregate parts of your application rather than to simplify control creation. Controls should be simple and have a single purpose for which they are designed.
When you create a ViewModel for your UserControl, you also break the natural flow of data via the DataContext. This is where you will experience the most pain. To demonstrate, consider this simple example.
We have a ViewModel that contains People, each being an instance of the Person type.
public class ViewModel
{
public IEnumerable<Person> People { get; private set; }
public ViewModel()
{
People = PeopleService.StaticDependenciesSuckToo.GetPeople();
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
To show a list of people in our window is trivial.
<Window x:Class="YoureDoingItWrong.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:YoureDoingItWrong"
Title="Derp">
<Window.DataContext>
<l:ViewModel />
</Window.DataContext>
<Window.Resources>
<DataTemplate DataType="{x:Type l:Person}">
<l:PersonView />
</DataTemplate>
</Window.Resources>
<ListView ItemsSource="{Binding People}" />
</Window>
The list automatically picks up the correct item template for the Person and uses the PersonView to display the person's information to the user.
What is PersonView? It is a UserControl that is designed to display the person's information. It's a display control for a person, similarly to how the TextBlock is a display control for text. It is designed to bind against a Person, and as such works smoothly. Note in the window above how the ListView transfers each Person instance to a PersonView where it becomes the DataContext for this subtree of the visual.
<UserControl x:Class="YoureDoingItWrong.PersonView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<StackPanel>
<Label>Name</Label>
<TextBlock Text="{Binding Name}" />
<Label>Age</Label>
<TextBlock Text="{Binding Age}" />
</StackPanel>
</UserControl>
For this to work smoothly, the ViewModel of the UserControl must be an instance of the Type it is designed for. When you break this by doing stupid stuff like
public PersonView()
{
InitializeComponent();
this.DataContext = this; // omfg
}
or
public PersonView()
{
InitializeComponent();
this.DataContext = new PersonViewViewModel();
}
you've broken the simplicity of the model. Usually in these instances you end up with abhorrent workarounds, the most common of which is creating a pseudo-DataContext property for what your DataContext should actually be. And now you can't bind one to the other, so you end up with awful hacks like
public partial class PersonView : UserControl
{
public PersonView()
{
InitializeComponent();
var vm = PersonViewViewModel();
// JUST KILL ME NOW, GET IT OVER WITH
vm.PropertyChanged = (o, e) =>
{
if(e.Name == "Age" && MyRealDataContext != null)
MyRealDataContext.Age = vm.PersonAge;
};
this.DataContext = vm;
}
public static readonly DependencyProperty MyRealDataContextProperty =
DependencyProperty.Register(
"MyRealDataContext",
typeof(Person),
typeof(PersonView),
new UIPropertyMetadata());
public Person MyRealDataContext
{
get { return (Person)GetValue(MyRealDataContextProperty); }
set { SetValue(MyRealDataContextProperty, value); }
}
}
You should think of a UserControl as nothing more than a more complex control. Does the TextBox have its own ViewModel? No. You bind your VM's property to the Text property of the control, and the control shows your text in its UI.
MVVM doesn't stand for "No Codebehind". Put your UI logic for your user control in the codebehind. If it is so complex that you need business logic inside the user control, that suggests it is too encompassing. Simplify!
Think of UserControls in MVVM like this--For each model, you have a UserControl, and it is designed to present the data in that model to the user. You can use it anywhere you want to show the user that model. Does it need a button? Expose an ICommand property on your UserControl and let your business logic bind to it. Does your business logic need to know something going on inside? Add a routed event.
Normally, in WPF, if you find yourself asking why it hurts to do something, it's because you shouldn't do it.

- 1
- 1
-
12This answer is _really_ hard for me to understand. First you write _"UserControls should NOT have ViewModels designed specifically for them"_. Then you write _"the ViewModel of the UserControl must be an instance of the Type it is designed for"_. First, how does any of this preclude using more than one view model in a window, e.g. bound to different `UserControl`s (as the OP's _actual_ question) or even other types of control? Second, inasmuch as there must be knowledge in the `UserControl` of the object to which it's bound, how does one avoid "designing for" exactly that? – Peter Duniho Mar 25 '15 at 15:29
-
2@peterduniho 1) I have a MainWindowViewModel that contains Person models in a Persons property. My PersonUserControl should be designed to display information in a Person model. It should not have a PersonUserControlViewModel which somehow takes a Person instance and kludges it into the PUCVM's properties to which elements in the PersonUserControl is bound. See how that second path becomes a PITA? The UserControl should be designed with the assumption its DataContext is a Person. – Mar 25 '15 at 15:39
-
@PeterDuniho 2) I'm answering the question "Should a user control have it's own ViewModel?", not the false dichotomy within the body of his question. 3) Of course you design for a model. You shouldn't design a ViewModel specifically for your UserControl. You're conflating a Model or even a ViewModel that is organic within the system to a ViewModel designed to support a UserControl. Again, think about it--does a TextBox have a TextBoxViewModel? No, it displays and edits Strings. Does a PersonUserControl have a PUCVM? No, it displays and edits Person instances. – Mar 25 '15 at 15:44
-
6Not sure I agree. If your user control just presents data, then do it all in the code behind. However, if you have some more complex UI logic whereby a control can affect other controls within the composite control, why not put that logic in a POCO (ViewModel) that you can easily unit test. Yes, your View is coupled to a ViewModel, but that ViewModel is designed specifically for that View - they exist as a pair. It's not difficult to set up such that you can access both you dependency properties and view model properties. – James B Jun 25 '15 at 12:40
-
1@JamesB I don't particularly care about crazy corner cases where it *might* be *slightly* useful to do this as 99% of the time you end up causing yourself more harm than good. – Jun 25 '15 at 12:55
-
7Not sure that testing UI logic should be considered a crazy corner case. Afterall, isn't one of the tenets of MVVM to remove UI logic from the view and put it into the ViewModel so that you can test it - *"Moving the UI logic to a separate class that can be instantiated independently of a UI technology makes unit testing much easier"* ([MSDN](https://msdn.microsoft.com/en-us/library/hh848246.aspx)). Your answer states "incorrect to use ViewModels to contain UI logic" - that's not what MSDN encourages us to do. I would argue its far more than slightly useful to test your VMs. – James B Jun 26 '15 at 09:29
-
@JamesB I don't think that's correct at all. MVVM != no codebehind. Besides, can you find me one example of a WPF control in the framework that has a ViewModel? Just one? I'll wait. – Jun 26 '15 at 15:22
-
3100% agree that MVVM != no code behind (I never said that it did???). For simple controls that just present data there would be little gained from implementing a ViewModel. However, IMHO, if you're putting together more complex controls, then you probably ought to be testing them and you'll need a ViewModel to do that. Each to their own, but all I'm saying is that we've found it highly beneficial to use VMs with some of our composite controls. It just depends on your use case, and the test coverage you're after. – James B Jun 29 '15 at 10:16
-
1I Agree on @JamesB 's comments , I as well have viewmodels behind some User Controls, it just depends how you use them. If you only have that user control to display some data in a list, yes, then you don't need a viewModel. However, if your User Control contains more then that like image display, some data and some buttons (a typical side panel). Then I do create a viewModel. In this case it mostly only needed to forward some commands to a singleton class and listen to some events of that singleton class to update the binded UI properties. – CularBytes Mar 05 '16 at 17:15
-
6@Will, I agree with the points you are making because I have experienced the pain you are talking about. But I still don't know if it's the right answer – you said: "If you're placing business logic in the UserControl, most likely you are using it to segregate parts of your application rather than to simplify control creation." What do you propose as the solution to this case? For example, imagine a suite of applications that all share a common control and some common business logic for that control. Should the consuming applications really have to hook those two things together themselves? – Adam Goodwin Jan 08 '18 at 11:49
-
Maybe I should rephrase my comment – "Imagine a suite of applications that all share a common view, and some common business logic in a view model used by that view. Should the consuming applications really have to hook up that view and view model themselves, every time one of them wants to use it? (Or even worse, should each application have to implement the view model itself?)" – Adam Goodwin Jan 08 '18 at 12:07
-
When you wrote "For this to work smoothly, the ViewModel of the UserControl ..." did you mean "...the DataContext of the UserControl..." instead? – StayOnTarget Apr 30 '19 at 17:38
-
In MVVM for WPF, the DataContext holds the ViewModel, so yes, indirectly. – Apr 30 '19 at 18:12
-
Good answer, though little less sass goes a long way! – Zimano Nov 10 '20 at 15:26
-
2"Normally, in WPF, if you find yourself asking why it hurts to do something, it's because you shouldn't do it." great reminder! also thnx for the in depth explanation! Helped a lot – Daanvl Mar 10 '21 at 11:03
-
As someone just starting out with WPF this answer was really helpful in making the conceptual transition. Thanks. – stigzler Sep 21 '22 at 19:48
This is not a yes or no question. It depends on whether having extra view models affords you better maintainability or testability. There's no point adding view models if it doesn't gain you anything. You'll need to gauge whether the overhead is worth it to your particular use case.

- 175,602
- 35
- 392
- 393
-
5Your answer contrasts heavily with @Will's answer. His seems to make more sense: usercontrols are still just essentially controls. I'm curious if you've changed your opinion since '09 when you wrote this answer. – Lynn Crumbling Mar 18 '15 at 13:37
-
1Think testing. If your control has some complex logic, why not stick it in a ViewModel and test it. – James B Jun 25 '15 at 12:42
[should] each user control have its own ViewModel or should the window as a whole have only one ViewModel?
Unfortunately, the highest-voted answer to this question is misleading, and based on comments I've exchanged in other questions, providing poor guidance to people trying to learn WPF. That answer replies:
Your UserControls should NOT have ViewModels designed specifically for them.
The problem is, that's not the question that was asked.
I would agree with the general sentiment that when you write a UserControl
, the public API of the control should not involve creating also a view model type that is specifically designed to be used for that control. The client code must be able to use whatever view model it wants.
But, that does not preclude the idea that "each user control [might] have its own ViewMomdel". There are at least two obvious scenarios I can think of where the answer to that would be "yes, a view model for each user control":
The user control is part of a data template in an items presenter (e.g.
ItemsControl
). In this case, the view model will correspond to each individual data element, and there will be a one-to-one correspondence between the view model object and the user control that presents that view model object.
In this scenario, the view model object is not "designed specifically for them" (so no contradiction with the questionable answer), but it certainly is the case that each user control has its own view model (making the answer to the actual question "yes, each user control may have its own view model").The user control's implementation benefits from, or even requires, a view model data structure specifically designed for the user control. This view model data structure would not be exposed to the client code; it's an implementation detail, and as such would be hidden from the client code using the user control. But, that certainly still would be a view model data structure "designed specifically for" that user control.
This scenario is clearly not problematic at all, which directly contradicts the claim that "Your UserControls should NOT have ViewModels designed specifically for them."
Now, I don't believe it was ever the intent of the author of that answer to rule out either of these scenarios. But the problem is, people who are trying to learn WPF may not have enough context to recognize the difference, and thus may incorrectly generalize with respect to user controls and view models, based on this emphatic, highly-upvoted, and misleading answer.
It is my hope that by presenting this alternative view point as a point of clarification, and answering the original question in a less narrow-viewed way, those who found this question while learning more about WPF will have better context, and a better idea and when a view model might be implemented specific to a user control and when it should not be.

- 68,759
- 7
- 102
- 136
-
1In scenario 2, if you have a ViewModel created specifically for a user control and wish to hide it from the client, how do you set it as the DataContext for the User Control? You don't want that happening in the XAML because it would be up to the client to add it when using your control. You don't want to do `this.DataContext = this; // omfg` (stupid stuff according to the popular answer you refer to) either. – Étienne Laneville Sep 23 '19 at 21:33
-
2@ÉtienneLaneville: _"how do you set it as the DataContext for the User Control?"_ -- you don't. You should not modify the top-level `UserControl.DataContext` property, as that's the property the client code can see and likely will want to modify. Instead, you would want to set the `DataContext` property of some element _inside_ the `UserControl`. The `UserControl` will necessarily have a single top-level element as its content (e.g. `StackPanel`, `Grid`, whatever), and that would be a fine element on which to set the `DataContext`. Alternatively, one or more child elements inside that. – Peter Duniho Sep 23 '19 at 21:50
-
1I see, so instead of something like `
-
@ÉtienneLaneville: yes, that's right. Ideally, there'd be a container element where it's natural to add one view model object that can apply to the entire user control. But there will always be exceptions, where one might want/need to provide an element-specific view model to e.g. a `Button` or something. To be clear: once we accept that the `UserControl.DataContext` property is off-limits, we're pretty much back to the question asked here, and of course that means being open to either possibility: a single view model for the entire component or element-specific view model objects. – Peter Duniho Sep 23 '19 at 22:17
-
@PeterDunhino if we set the DataContext of a UserControl to our View Model and the client then sets it something else, that clears out our ViewModel then? That's why you would add it to the top internal element inside the UserControl instead, where it will override the new DataContext? – Étienne Laneville Sep 23 '19 at 22:33
-
@ÉtienneLaneville: _"that clears out our ViewModel then"_ -- yes, the `DataContext` property can only reference one object at a time. _"where it will override the new DataContext"_ -- again, yes...note that the client code's view model is there solely for binding to your user control's public dependency properties. So you don't need it as a context within the user control implementation itself. Overriding the context in a child element is fine in that case. – Peter Duniho Sep 23 '19 at 22:36
I would say that each user control should have its own ViewModel, because that would allow you to reuse the ViewModel/UserControl pair in new constellations in the future.
As I understand it, your window is a Composite of user controls, so you can always create a ViewModel that composes all the separate ViewModels for each of the user controls. This will give you the best of both worlds.

- 225,310
- 48
- 427
- 736
-
2Your answer contrasts heavily with @Will's answer. His seems to make more sense: usercontrols are still just essentially controls. I'm curious if you've changed your opinion since '09 when you wrote this answer. – Lynn Crumbling Mar 18 '15 at 13:41
-
9Will seems pretty adamant, but I err on Mark's side. To me there is no reason why a control can't have its own view model: you just have have to appreciate that they exist as a coupled pair. We bind views to view models all the time and pragmatically speaking a one-to-one relationship exists between a view and its view model (one to many for a view model and model). For simple views that just present data do it in the code behind. If there is logic involved, why not do it in a View Model so you can do some all important unit testing. – James B Jun 25 '15 at 12:25
I'd be inclined toward a viewmodel.
Bear in mind that all of these patterns are designed to fragment your code to make it more maintainable in the future. Including MVVM. The view has certain responsibilities, so too the viewmodel, so too the model. A fresh developer can come in, can recognise this pattern, will have a better idea where to find and maintain things. Better than if it were a heap of spaghetti.
So, within that, if you have logic which correctly pertains to the usercontrol, which correctly belongs in the vm, then why not?
But there is a caveat here. Bear in mind what a UserControl is. It's something that is a tiny snippet of UI that can be reused from place to place. Your vm should be the same - reusable. The last thing you want to end up with is a vm which behaves one way in one scenario, and a different way in another scenario.
Note, no technology talked. I'm just talking about the logical structure of the pattern.

- 2,394
- 1
- 20
- 29
I guess your application is doing some sort of view composition, so if you make your user controls to have its own view model, you'll have more freedom to embed them in other host windows without changing the window global view model.
As an added bonus, your application will be more suited to evolve to a more architecturally-sound composition model as that provided by Prism or Caliburn frameworks, if the application requirements arise.

- 812
- 1
- 7
- 13