views:

494

answers:

3

What is the best practice to load an UserControl into an Window with MVVM-Light? Where create the UserControl instance, in the ViewModel from Window or direct in the window?

+2  A: 

Your VM should not contain any UI specific code like controls if you are worried about best practice. For example, if you have a property in the VM that controls the visibility of a control in your view, that property should be of type bool and not Visibility. The view will use the bool property to hide or show the control.

So you have a view (like a window) which databinds against a VM. Some property changes in the VM which will cause some code in the window to create and show a user control.

Wallstreet Programmer
A: 

I will be happy if you can show an example of doing in using mvvm light. I also have the problem want main window with "child window" (user controls) to show/ hide on button click from the mainwindow.. so should i create them all in the same place let's say grid column and then male them show/hide by property binding?

Shirly
+1  A: 

I just read this excellent post about creating a tabbed interface with MVVM (Light). It doesn't talk about user controls, but the goal is quite close. It would be easy to modify to support user controls.

The approach is to bind the tab control to an observable collection of Workspaces (ViewModels). When a new tab (or workspace) is added, it's instantiated in the ViewModel, added to the collection, databound to the View and rendered as a new tab with the help of DataTemplates.

Jemm