Question

As I knock off more and more MVVM-related issues with my current application, more just keep popping up. :)

The current implementation that I am trying to replace involves a StackPanel whose children are more or less dynamically generated (via looking in a configuration file). Each child is an instance of a UserControl. Before, what I did was assign a name to the StackPanel, and then in the Window_Loaded event handler, I'd simply determine the necessary number of children, instantiate one UserControl for each, and also assign the UserControl an ID so I'd know the proper source for the Buttons clicked on a particular UserControl instance; each UserControl has 3 buttons on it.

So I know I want to bind the StackPanel to a collection. This of course, is not possible, as I need to use something that derives from ItemsControl, like ListBox or ListView (or even ItemsControl itself). To keep it easy in the first iteration of MVVM-ifying, I'll just use a ListBox.

Now the question is, should my ObservableCollection in the code-behind be a ObservableCollection? I believe this means that no matter how I skin my GUI, this ListBox will always have children that look however they do in MyUserControl's XAML file. I'd like this to be customizable as well, but I assume this means I have to apply the MVVM pattern to the UserControl as well.

Was it helpful?

Solution

If you want each of your list items to have different templates, and want to stick to an MVVM style, you're better off not thinking in terms of UserControls.

You can have your main view to have a ListBox bound to an observable collection of View Model instances. If you setup your data templates to map the ViewModel classes to their appropriate UserControl, you don't need to ever explicitly load UserControls - just bind any ItemsControl to your collection of ViewModels, and let the data templates take care of constructing and mapping this to the correct UserControl for that VM.

OTHER TIPS

Your collection doesn't have to be an ObservableCollection if it doesn't have to. The "Observable" part of ObservableCollection is simply a matter of supplying events to notify others that the collection has changed, it is by no means related to visual representation.

ObservableCollection is very well suited for MVVM because of all the event notification it supplies, but ultimately, whether you use a List<T> or an ObservableCollection<T> makes no difference in the way things appear visually at any given point in time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top