Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM - Controls versus Views

I've been doing a prototype in WPF without using MVVM. It's got to such a size now that I'm refactoring it to use MVVM.

When I started the project, I jumped straight in and created UserControls for lots of things.

I'm now breaking things in Views and ViewModels. But, I'm ending up with Views that contain UserControls; the UserControls have bindings to what are now objects in the Model.

So, is the notion of UserControls now dead in MVVM? What I mean is, in the past (WinForms, ASP.NET etc.) you'd have a project called 'Controls' and reuse these. Is the 'View' in MVVM a direct replacement of the typical UserControl?

like image 986
Steve Dunn Avatar asked Jan 24 '23 11:01

Steve Dunn


2 Answers

A UserControl in WPF is little more than a ContentControl with a few tweaked default property values. A ContentControl is little more than a piece of content that can have a template applied to define its look.

The way I do MVVM skips the middleman and defines views as DataTemplates. Then you need only stick your VM into WPF's visual tree somewhere, and WPF will render it with your DataTemplate. For example:

<ContentControl Content="{Binding SomeViewModel}"/>

<ItemsControl ItemsSource="{Binding SomeViewModels}"/>
like image 83
Kent Boogaart Avatar answered Jan 28 '23 14:01

Kent Boogaart


The way I see UserControls in the MVVM world is as a View. Rather than thinking of your WPF form as a single view, you can think of it as a composite of one or more views. So a UserControl can encapsulate a standard re-usable view that can be incorporated into multiple composite views. Great for re-usability and still they're still testable.

like image 44
Paul Alexander Avatar answered Jan 28 '23 14:01

Paul Alexander