1

我有这个列表框,我想搜索用户选择的项目(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 对象!!,那么我该如何迭代 selected(IsChecked=true) items(staffs) ...

肿瘤坏死因子

4

1 回答 1

3

如何:在 MSDN 上查找 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;

您必须将 设置SelectionModeMultipleExtended以使其正常工作。

于 2013-10-08T10:51:48.913 回答