How to get selected items from listbox has checkboxes in WPF?

13,315

It would probably be best to bind the CheckBox to the IsSelected property of the ListBoxItem, like so:

<DataTemplate>
    <CheckBox Content="{Binding .}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" />
</DataTemplate>

Then you can get the checked/selected items from the ListBox.SelectedItems collection. You'd also have to set SelectionMode to Multiple.

Share:
13,315
kartal
Author by

kartal

Updated on July 27, 2022

Comments

  • kartal
    kartal almost 2 years

    This is the ListBox code:

    <ListBox x:Name="courseslistview" 
             ItemsSource="{Binding .}" 
             FontSize="18.667" 
             FontFamily="Trebuchet MS" 
             LayoutUpdated="courseslistview_LayoutUpdated">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding .}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    

    How can I use C# to get all the checked checkboxes in the above ListBox?

  • Balasubramani M
    Balasubramani M almost 10 years
    Am working on WP app and i get the following error. The property 'AncestorType' was not found in RelativeSource and 'AncestorType' is not recognized or it not accessible. Can you also give solution for how it comes in Windows Phone?
  • CodeNaked
    CodeNaked almost 10 years
    @BalasubramaniM - This question is specific to WPF. I'd recommend asking a separate question, if it hasn't already been asked before.
  • SANDEEP
    SANDEEP over 8 years
    and how to get checked checkbox value
  • CodeNaked
    CodeNaked over 8 years
    The items that are checked would be the in ListBox.SelectedItems collection. Any that are not in that collection would not be checked.