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

懵懂的女人 提交于 2019-12-30 06:46:28

问题


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?


回答1:


It would probably be best to bind the CheckBox to the IsSelected property of the ListBoxItem, like so:

<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. You'd also have to set SelectionMode to Multiple.



来源:https://stackoverflow.com/questions/6525920/how-to-get-selected-items-from-listbox-has-checkboxes-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!