#980 – Binding ListBox Selection to Property on Bound Object

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());
        }

980-001

Advertisements