Adding/removing usercontrol dynamically

Jan 10, 2012 at 6:46 AM

How do I add usercontrol(s) to the view during runtime using MVVM? Is it possible to do it without using code-behind?

I basically have three options displayed in a comboBox. When a user selects one of them and click "Load" button, corresponding usercontrol needs to be added to the view. It could be in listbox or a stackpanel. Also if it is in a listbox, when a user selects a ListboxItem (usercontrol) and clicks "Delete/Remove", it should be removed from the listbox.

Many thanks!

Jan 11, 2012 at 3:50 PM
Edited Jan 11, 2012 at 3:52 PM

I would create a child ViewModel that contains with a child UserControl bound to it.  The ListBox would have a DataTemplate with an ItemSource bound to an ObservableCollection of child ViewModels.  Hope this points you in the right direction ...

However, if you do need to use code-behind, I don't consider that necessarily to be at odds with MVVM.  The question I ask myself with MVVM is whether the ViewModel is testable.

Jan 11, 2012 at 11:42 PM

Hi Tony,

For now, I have added the usercontrol in the listbox using the Notification mechanism in the toolkit using the code behind. The idea of creating child viewmodels seems interesting. I have never done it this way. Would you or someone following this could post an example?

Many thanks!