Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TwoWay Manual Binding Implementation for ListBox.SelectedItems?

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

Update: the above mentioned blog is no longer available, that author's current blog is here and the closest I could find to the referenced blog post is this StackOverflow answer.

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?

like image 636
robcecil Avatar asked Jan 05 '09 18:01

robcecil


1 Answers

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.

like image 83
Samuel Jack Avatar answered Oct 20 '22 19:10

Samuel Jack