2010-10-28 143 views
1

上午在列表框中的项目使用复选框,如何从列表中获取选中复选框如何获得所选项目在WPF复选框列表框

<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()); 
      } 
     } 
    } 
+0

什么是异常和从哪一行抛出的异常? – 2010-10-28 02:55:17

回答

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

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

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

你可以移动对每个项目从UI远的数据上下文和创建对象

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 */ 
} 

然后在你的列表框的一个ObservableCollection的ItemTemplate

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

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

+0

这就是我在过去+1中实施过的。一个小问题:如果需要双向绑定,您可能希望在您的'CheckedItem'上实现'INotifyPropertyChanged'。 – 2010-10-28 08:00:15

+0

在INotifyPropertyChanged上达成一致。它确实取决于你的要求 – benPearce 2010-10-28 21:02:16

0

我会建议这样的代码:

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