#980 – Binding ListBox Selection to Property on Bound Object
January 6, 2014 1 Comment
Normally, when you use a ListBox, the ListBox itself persists the record of which items are selected. You might also want to persist information about which items are selected within the actual data objects that you’re binding to.
You can bind the IsSelected property of each list box item to a boolean property on the data object as shown below.
<ListBox Name="lbActors" Margin="15" Width="200" Height="190" SelectionMode="Multiple" ItemsSource="{Binding ActorList}"> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="IsSelected" Value="{Binding IsFav}"/> </Style> </ListBox.ItemContainerStyle> </ListBox>
Now, as you select/unselect items, the IsFav property in the corresponding Actor object is set or cleared. Also, when your application starts, the ListBox selection will initially be set to reflect the value of this property.
private void Button_Click(object sender, RoutedEventArgs e) { StringBuilder sbInfo = new StringBuilder(); // Who are favorites? foreach (Actor a in lbActors.Items) { if (a.IsFav) sbInfo.AppendLine(a.FullName); } MessageBox.Show(sbInfo.ToString()); }
Actually this implementation isn’t suitable for lists which have big amount of items (e.g. 2-5 k). I tried to bind to IsSelected property of each item in ListBox/DataGrid and there was big performance hit when you press CTRL + A.
The solution was to write custom behavior which hooks to ListBox/DataGrid selection related events and propagates selection changes where it’s needed (view model in my case).