I was asked the other week how I'd implement a view-model that binds to two combo boxes in the view, where a selection in one affects the other. I've called it category & sub-category combo boxes but I guess it could also be called parent-child combo boxes.
Now I don't perceive this as particularly complex to do, but I was asked how would I do it?
Would I use two seperate lists and how would I avoid stack overflow exceptions when raising property changed events.
The UI looks like this:
The categories are represented by the top combo box:
The sub categories are represented by the bottom combo box:
You should be able to infer from the screen shots that each category has a set of sub-categories, the only special category is All -
when selected then all sub categories are displayed, as shown above.
So when Category A
is selected then only the related sub-categories should be displayed:
I used a dictionary &
linq to achieve the behaviour required, I avoided using two separate lists. The constructor & class parameters are shown below. As you can see there are only 2 parameters - one for the selected category and the other for the selected sub-category:
The example data pumped into the view-model looks as follows:
I've host the code on sky-drive but I've highlighted the properties on the view-model below starting with the simplest the Categories
property. As you can see this is very simple:
It starts to get interesting with the SelectedCategory
property, when the property is being set it clears the selected sub-category if the currently selected sub-category is not part of the selected category and then always notifies the of changes to the SubCategories
property is either a linq if the selected category is either All
or empty\null, or just the value from the dictionary:
The final property is SelectedSubCategory
, simply if the selected category is All
then do nothing else if the selected category does not contain the selected sub-category then find the one that does:
Post a Comment