views:

3669

answers:

1

Hello,

I've been trying to see if there is an easy/clever way to implement binding to ListBox.SelectedItems. If you have tried yourself, you will know, that markup binding using BindingExtension will not work - the property doesn't support it. So you are left with wiring up a handler for SelectionChanged and trying that route. The closest I've gotten is this post:

http://alexshed.spaces.live.com/blog/cns!71C72270309CE838!149.entry

Which implements all the necessary C# in a handy attached property. But it implements the "binding" as a One-Way, Target to Source. I'd like Two-Way binding.

Any ideas?

+15  A: 

I've found an elegant solution, and I've just found time to write a blog post about it.

What I did was to create an attached property, SynchronizedSelectedItems that you can set on the ListBox (or DataGrid in fact). You databind this to a collection, and then, with a bit of magic, the SelectedItems property on the ListBox and your collection are kept in sync. You can download all the code from my blog post.

The "magic" is a class which listens out for CollectionChanged events in either collection, and propagates the changes to the other.

Samuel Jack
Thanks, that really helped.
Echilon
just great - really good stuff
headsling