views:

618

answers:

4

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?

A: 

Mmmm... when I had user controls I just passed the DataContext from the View to the user control (the subinfo needed by that user control). But is true, that sometimes is hard to fit ViewModel with Views, UserControls, ...

Braulio
A: 

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.

Paul Alexander
+5  A: 

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}"/>

HTH, Kent

Kent Boogaart
That's exactly what I do Kent, but there's no reason you can't wrap a UserControl in a DataTemplate and let binding do its thing, right?
Scott Whitlock
A: 

Regarding Paul's answer,

I'm trying to design a SCADA like application using WPF and MVVM. My idea is to have User Controls as Views. But how would I design the application if I don't know what views and view models would I have at design time? I was thinking to have an XML configuration file based on which I would construct the user interface with different views (User Controls).

Any suggestion?

Thank you.

electro
Please take a look at this demo of an extensible application using WPF and MVVM: http://www.codeproject.com/KB/WPF/SoapBoxCorePinBallDemo.aspx That should let you do what you want.
Scott Whitlock
Thank you Scott. I had a brief look at the page and it just might be what I need. I appreciate your help.
electro