简体   繁体   English

如何从列表框中获取所选项目在 WPF 中有复选框?

[英]How to get selected items from listbox has checkboxes in WPF?

This is the ListBox code:这是列表框代码:

<ListBox x:Name="courseslistview" 
         ItemsSource="{Binding .}" 
         FontSize="18.667" 
         FontFamily="Trebuchet MS" 
         LayoutUpdated="courseslistview_LayoutUpdated">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding .}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

How can I use C# to get all the checked checkboxes in the above ListBox?如何使用 C# 获取上述列表框中的所有选中复选框?

It would probably be best to bind the CheckBox to the IsSelected property of the ListBoxItem , like so:最好将CheckBox绑定到ListBoxItemIsSelected属性,如下所示:

<DataTemplate>
    <CheckBox Content="{Binding .}" IsChecked="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, Path=IsSelected}" />
</DataTemplate>

Then you can get the checked/selected items from the ListBox.SelectedItems collection.然后您可以从 ListBox.SelectedItems 集合中获取选中/选定的项目。 You'd also have to set SelectionMode to Multiple.您还必须将SelectionMode设置为 Multiple。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM