Lucaribou
Lucaribou

Reputation: 294

Binding ObservableCollection to selected items of a ListBox

After hours and hours of googling, I still can't find a simple solution for binding an ObservableCollection to the selected items of a ListBox in a TwoWay Mode...

What I have is really simple : a ListBox with SelectionMode="Multiple", and an ObservableCollection<Contact> named SelectedContacts. I want this two to be bound. Of course my ListBox has ItemsSource="{Binding Contacts}" which is another ObservableCollection of Contact.

Now I really can't use a IsSelected bool on my Contact items, I just can't.

Thank you !

Upvotes: 3

Views: 3156

Answers (3)

Lee O.
Lee O.

Reputation: 3312

Another option is to not keep track of the selected items in your ViewModel. Instead, pass them as a CommandParameter from the UI when you are trying to do some action.

Example:

<ListBox x:Name="MyListBox" 
         ItemsSource="{Binding SomeCollection}" />
<Button Command="{Binding SomeCommand}" 
        CommandParameters="{Binding SelectedItems, ElementName=MyListBox}" />

Upvotes: 0

jcvegan
jcvegan

Reputation: 3170

Since SelectedItems is not a DependencyProperty you are not allowed to use Bindings

But there is a solution, take a look at this post: http://blogs.microsoft.co.il/miziel/2014/05/02/wpf-binding-listbox-selecteditems-attached-property-vs-style/

Upvotes: 1

BradleyDotNET
BradleyDotNET

Reputation: 61339

There is no simple solution. You can't bind SelectedItems.

The best solution is to select your Contact items into a view model object with an IsSelected property, bind to that, and then run a query against the primary OC when you need to get the selected items collection.

Since you said you can't/won't do that, the next best solution would likely be to handle SelectionChanged in your code-behind and manually update the VM collection from there.

Upvotes: 3

Related Questions