I am new to both WPF and MVVM so I will beg forgiveness upfront if this is a silly question.
Problem:
I am trying to create a grouped list of items using the MVVM design pattern. I can do it with code behind, but would prefer a more elegant solution.
Details
- Let’s say I have a collection of animals: horse, wolf, monkey, tiger, polar bear, zebra, bat, etc.
- These animals are grouped by continents: North America, Africa, Antarctica, etc.
Goal: Within a wrap panel, I would like to create grouped toggle buttons. For example, there would be a “North America” GroupBox with ToggleButtons for each animal found in North America. Next, there would be a GroupBox with the header “Africa” and inside the group box would be all the animals in Africa.
Using the MVVM design pattern, I can bind to an ObservableCollection and, using a data template, create the toggle buttons I need. Where I’m struggling is I don’t know how to group the animals. All I need are guidelines to follow. Any help would be appreciated.
In the View, set the items source to a CollectionViewSource that itself binds to the Animals collection on the ViewModel. The CollectionViewSource can be grouped, something like this:
You’ll also need to set a group style on whatever items control you’ve got – something like this
Taken from the example on this page – http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.groupstyle.aspx
That’s setting the HeaderTemplate, but if you play around a bit you should be able to set a container style for each group.
Hope this helps!
Update:
I wasn’t too sure about this so I had a quick bash at the code. Assuming ‘toggle button’ is ‘radio button’, this is what I’ve come up with:
In addition, you can display each group as a GroupBox by replacing the line
<x:Static Member="GroupStyle.Default" />with:However, the radio buttons will not be mutually exclusive on their own (I presume because they are wrapped in ListItem controls, or something else that makes them a single child of a grouping parent). That code was stolen/modified from the GroupStyle entry in MSDN if you want to go back for more information (their example had expanders to show/hide groups): http://msdn.microsoft.com/en-us/library/system.windows.controls.groupstyle.aspx
Let me know if I’ve missed the point at all.