I have a multi-select listbox in a SL3 app using prism and I need a collection in my viewmodel that contains the currently selected items in the listbox.
The viewmodel doesn’t know anything about the view so it does not have access to the listbox control. Also I need to be able to clear the selected items in the listbox from the viewmodel.
Not sure how to approach this problem
thanks
Michael
So, assume you have a ViewModel with the following properties:
You would start by binding your AllItems collection to the ListBox:
The problem is that the SelectedItems property on ListBox is not a DependencyProperty. This is pretty bad, since you can’t bind it to something in your ViewModel.
The first approach is to just put this logic in the code-behind, to tweak the ViewModel:
This approach will work, but it is really ugly. My preferred approach is to extract this behavior into an “Attached Behavior”. If you do that, you can completely eliminate your code-behind and set it up in the XAML. The bonus is that this “Attached Behavior” is now re-usable in any ListBox:
And here is the code for the Attached Behavior: