#981 – Including a CheckBox with Each Item in a ListBox

By default, a ListBox shows the selection state of each item in the list using a different brush.  If you want to make the selection of each item more obvious and not force the user to use Ctrl or Shift keys to multi-select items, you can render each item as a CheckBox.

Assume that we bind to a a list of Actor objects, where Actor has IsFav (boolean) and NameAndDates (string) properties, you can do the following:

        <ListBox Name="lbActors" Margin="15" Width="200" Height="190"
                 ItemsSource="{Binding ActorList}">
            <!-- Because CheckBox indicates selection, hide standard ListBox -->
            <!-- selection behavior -->
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Focusable" Value="False"/>
                </Style>
            </ListBox.ItemContainerStyle>
            <!-- Each item in list is a CheckBox -->
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <CheckBox Content="{Binding NameAndDates}" IsChecked="{Binding IsFav}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

As you check each item, the IsFav property in the corresponding Actor object is set/cleared.

981-001

Advertisement