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

Spe*_*n D 1 c# wpf checkbox listbox

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>
Run Code Online (Sandbox Code Playgroud)

我试图循环通过listboxitems中的选定项目,但它在listboxitem中抛出异常

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

ben*_*rce 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 */
}
Run Code Online (Sandbox Code Playgroud)

然后在ListBox ItemTemplate中

<ItemTemplate>
  <DataTemplate>
    <CheckBox IsChecked="{Binding Path=Selected}" 
              Content={Binding Path=Description}" />
  </DataTemplate>
</ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

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