Many moons ago, I asked on the WPF forums if anybody had a way of data-binding the Selected Items property of a List Box.Standard data binding doesn’t work, because the Selected Items property is read-only, and understandably so: how would you like it if I injected an arbitrary collection into your List Box and expected you to keep it up to date as the selection changed?As no one gave me an answer, I was forced to use my gray-matter and invent a solution of my own.Since a similar question came up again recently on Stack Overflow, I thought I’d share what I came up with.
I won’t bore you with the code – see the download link below.
The XAML looks like this: using a data binding to my Selected Names property.
With that in place the Selected Names collection in my View Model is updated whenever Selected Items on the List Box changes.
And to prove it works the other way to, I’ve created a Select All command on the View Model that puts all available names into the Selected Names collection.
When you press the button you’ll see that the List Box obediently updates to show all items selected.