如何在WPF CheckBox ListBox中获取所选项目

时间:2010-10-28 02:49:16

标签: c# wpf listbox checkbox

Am使用列表框项目中的复选框,如何从列表中获取所选复选框

<ListBox ItemsSource="{Binding NameList}"  HorizontalAlignment="Left" Margin="16,68,0,12" Name="listBox1" Width="156" IsEnabled="True" SelectionMode="Multiple" Focusable="True" IsHitTestVisible="True" IsTextSearchEnabled="False" FontSize="12" Padding="5" SelectionChanged="listBox1_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate> 
                        <StackPanel Orientation="Horizontal">                      
                               <CheckBox Content="{Binding Path=CNames}" />
                        </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我尝试循环遍历listboxitems中的所选项目,但它在listboxitem中抛出异常

 private void btnSelected(object sender, RoutedEventArgs e)
    {
        foreach (ListBoxItem item in listBox1.Items)
        {
            if (item.ToString() == "true")
            {
                MessageBox.Show(item.Content.ToString());
            }
        }
    }

3 个答案:

答案 0 :(得分:5)

您可以将每个项目的数据上下文移离UI,并创建一个ObservableCollection对象

public ObservableCollection<CheckedItem> List { get;set;}

public class CheckedItem : INotifyPropertyChanged
{
  private bool selected;
  private string description;

  public bool Selected 
  { 
     get { return selected; }
     set 
     {
        selected = value;
        OnPropertyChanged("Selected");
     }
  }

  public string Description 
  { 
     get { return description; }
     set
     {
         description = value;
         OnPropertyChanged("Description");
     }
   }

  /* INotifyPropertyChanged implementation */
}

然后在ListBox ItemTemplate

<ItemTemplate>
  <DataTemplate>
    <CheckBox IsChecked="{Binding Path=Selected}" 
              Content={Binding Path=Description}" />
  </DataTemplate>
</ItemTemplate>

您选择的项目现在可在ObservableCollection中使用,而不是循环使用UI元素

答案 1 :(得分:1)

让你的模板像这样

<ListBox.ItemTemplate>
   <DataTemplate> 
 ........
   <CheckBox Content="" 
      IsChecked="{Binding IsSelected, Mode=TwoWay,
      RelativeSource={RelativeSource FindAncestor, 
      AncestorType={x:Type ListViewItem}}}"  />
 ..........
    <!-- Use Other UIElements to Show your Data -->

然后上面的绑定将与您的模型isSelected和列表视图选择同步两种方式,然后在代码中使用SelectedItems。

For Each s As myPoco In myListView1.SelectedItems
   ' do something here with
Next

答案 2 :(得分:0)

我会建议这段代码:

 private void save_Click(object sender, RoutedEventArgs e)
 {
     foreach (CheckBox item in list1.Items)
     {
         if (item.IsChecked)
         {
             MessageBox.Show(item.Content.ToString());
         }
     }
 }