Bahram
Bahram

Reputation: 1642

WPF Get CheckBoxes inside ListBox in code

I have this List box and I want to search for its items which were selected (IsChecked=true) by user

 <CheckBox Style="{StaticResource ResourceKey=CheckBoxes}"  
  Name="chkBoxSelectAllStaff" Content="Select All">                                                
  </CheckBox>


<ListBox Name="lstStaffs" MaxHeight="250" MinHeight="50" Margin="0,5,5,5" Width="350"
 ScrollViewer.VerticalScrollBarVisibility="Auto" HorizontalAlignment="Right"    
 HorizontalContentAlignment="Right">

<ListBox.ItemTemplate>
    <DataTemplate>
        <CheckBox Style="{StaticResource ResourceKey=CheckBoxes}" IsChecked="{Binding ElementName=chkBoxSelectAllStaff, Mode=OneWay, Path=IsChecked}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding FirstName}" Margin="0,0,3,0"></TextBlock>
                <TextBlock Text="{Binding LastName}" Margin="0,0,3,0"></TextBlock>
                <TextBlock Text="{Binding CellphoneNumber}" Margin="0,0,3,0"></TextBlock>
            </StackPanel>
        </CheckBox>
    </DataTemplate>
</ListBox.ItemTemplate>

I want to do something like this

 foreach(var item in lstStaff.Items){
    if((CheckBox) item).IsChecked){
          //do something
    }
 }

And also I am binding the data this way :

//staff is my entity object containing Id, FirstName, LastName, CellphoneNumber
lstStaffs.ItemsSource = args.Result; // comes from webservice call and is Staff[]
lstStaffs.UpdateLayout();

But I get Staff object in lstStaffs.Items!!, So how can I iterate over selected(IsChecked=true) items(staffs) ...

Tnx

Upvotes: 1

Views: 3620

Answers (1)

Sheridan
Sheridan

Reputation: 69979

From the How to: Find DataTemplate-Generated Elements page at MSDN:

// Getting the currently selected ListBoxItem 
// Note that the ListBox must have 
// IsSynchronizedWithCurrentItem set to True for this to work
ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.
    ContainerFromItem(myListBox.Items.CurrentItem));

// Getting the ContentPresenter of myListBoxItem
ContentPresenter myContentPresenter = FindVisualChild<ContentPresenter>(myListBoxItem);

// Finding textBlock from the DataTemplate that is set on that ContentPresenter
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName("textBlock", 
    myContentPresenter);

// Do something to the DataTemplate-generated TextBlock
MessageBox.Show("The text of the TextBlock of the selected list item: "
    + myTextBlock.Text);

This shows you how to get access to elements defined in a DataTemplate. However, if you just want to get access to the items from the collection that have been selected, there is a much simpler way:

var selectedItems = lstStaffs.SelectedItems;

You must set the SelectionMode to Multiple or Extended for this to work.

Upvotes: 3

Related Questions