2010-10-28 140 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()); 
     } 
    } 
} 
相關問題