首页 > 解决方案 > 如何从后面代码中的列表框中查询复选框?

问题描述

我有以下列表框:

<ListBox Grid.Column="0" BorderBrush="Black" Margin="15,20,122,15" MinHeight="25" Name="tbxFiles"
             VerticalAlignment="Stretch"
             ItemsSource="{Binding Items}"
             SelectionMode="Multiple" Grid.ColumnSpan="2">
                <ListBox.Resources>
                    <Style TargetType="ListBoxItem">
                        <Setter Property="OverridesDefaultStyle" Value="true" />
                        <Setter Property="SnapsToDevicePixels" Value="true" />
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate TargetType="ListBoxItem">
                                    <CheckBox Margin="5,2"
                                      IsChecked="{Binding IsSelected,RelativeSource={RelativeSource TemplatedParent}}">
                                        <ContentPresenter />
                                    </CheckBox>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </ListBox.Resources>
            </ListBox>

如您所见,我为 ListBox 中的每个项目创建了一个 CheckBox。但是现在我希望在单击按钮时将每个选中 CheckBox 的 ListBox Item 的文本打包到一个列表中。由于我对绑定不太熟悉,所以我问如何使用 IsChecked 绑定从后面的代码中访问它?

标签: c#wpfxamldata-binding

解决方案


不要向或 的源集合添加string值,您应该创建一个类,该类包含显示名称的属性和确定当前是否检查项目的另一个属性:tbxFiles.ItemsListBox

public class Item
{
    public string Name { get; set; } 
    public bool IsSelected { get; set; } 
}

然后将此类的实例添加到ListBox(或其源集合,具体取决于您是否使用绑定和 MVVM):

tbxFiles.Items.Add(new Item() { Name = System.IO.Path.GetFileName(filename) });

的可以用来定义 的ItemTemplate外观:ListBoxItem

<ListBox Grid.Column="0" BorderBrush="Black" Margin="15,20,122,15" MinHeight="25" Name="tbxFiles"
             VerticalAlignment="Stretch"
             SelectionMode="Multiple" Grid.ColumnSpan="2">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Name}"
                      IsChecked="{Binding IsSelected}" />
        </DataTemplate>
        </ListBox.Resources>
</ListBox>

获取当前选定的项目就像遍历源集合一样简单:

var selectedItems = tbxFiles.Items.OfType<Item>()
   .Where(x => x.IsSelected)
   .Select(x => x.Name);

推荐阅读