WPF在代码中获取ListBox内的CheckBoxes

时间:2013-10-08 10:44:51

标签: c# wpf listbox

我有这个列表框,我想搜索用户选择的项目(IsChecked = true)

 <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>

我想做这样的事情

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

而且我也是这样绑定数据:

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

但是我在lstStaffs.Items !!中获得了Staff对象,那么如何迭代选定的(IsChecked = true)项目(员工)......

TNX

1 个答案:

答案 0 :(得分:3)

来自MSDN的How to: Find DataTemplate-Generated Elements页:

// 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);

这将向您展示如何访问DataTemplate中定义的元素。但是,如果您只想访问已选择的集合中的项目,则有一种更简单的方法:

var selectedItems = lstStaffs.SelectedItems;

您必须将SelectionMode设置为MultipleExtended才能生效。