【问题标题】:How to get selected items from listbox has checkboxes in WPF?如何从列表框中获取所选项目在 WPF 中有复选框?
【发布时间】:2011-09-25 10:30:00
【问题描述】:

这是列表框代码:

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

如何使用 C# 获取上述 ListBox 中所有选中的复选框?

【问题讨论】:

    标签: c# wpf checkbox listbox


    【解决方案1】:

    最好将CheckBox 绑定到ListBoxItemIsSelected 属性,如下所示:

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

    然后您可以从 ListBox.SelectedItems 集合中获取选中/选中的项目。您还必须将 SelectionMode 设置为 Multiple。

    【讨论】:

    • 我正在使用 WP 应用程序,我收到以下错误。在 RelativeSource 中找不到属性“AncestorType”,并且无法识别或无法访问“AncestorType”。您能否也提供有关它在 Windows Phone 中的解决方案?
    • @BalasubramaniM - 这个问题特定于 WPF。如果以前没有问过,我建议单独问一个问题。
    • 以及如何获得选中的复选框值
    • 检查的项目将在ListBox.SelectedItems 集合中。任何不在该集合中的都不会被检查。
    猜你喜欢
    • 2017-06-09
    • 2015-10-20
    • 1970-01-01
    • 2011-08-02
    • 2013-05-17
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多