How to bind ListBoxItem.IsSelected to data boolean

I have a ListBox WPF in Extended SelectionMode.

I need to bind a ListBox to an observable collection of a data element class, which is easy, but essentially, bind the IsSelected status of each ListBoxItem to a Boolean property in the corresponding data element.

And I need it to be two-sided so that I can populate the ListBox with selected and unselected items from the ViewModel.

I reviewed a number of implementations, but no one works for me. These include:

  • Adding a DataTrigger to the ListBoxItem Style and Invoking a Change in State Action

I understand that this can be done in code with an event handler, but given the complexity of the domain, this would be terribly messy. I would rather stick with two-way snapping with ViewModel.

Thanks. Mark

+4
source share
1 answer

In WPF, you can easily bind your ListBox to a collection of items with a boolean property for the IsSelected state. If your question is about Silverlight, I am afraid this will not work easily.

 public class Item : INotifyPropertyChanged { // INotifyPropertyChanged stuff not shown here for brevity public string ItemText { get; set; } public bool IsItemSelected { get; set; } } public class ViewModel : INotifyPropertyChanged { public ViewModel() { Items = new ObservableCollection<Item>(); } // INotifyPropertyChanged stuff not shown here for brevity public ObservableCollection<Item> Items { get; set; } } 

 <ListBox ItemsSource="{Binding Items, Source={StaticResource ViewModel}}" SelectionMode="Extended"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsSelected" Value="{Binding IsItemSelected}"/> </Style> </ListBox.ItemContainerStyle> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding ItemText}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 
+10
source

All Articles