c# - 如何从后面代码中的列表框中查询复选框?
问题描述
我有以下列表框:
<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 绑定从后面的代码中访问它?
解决方案
不要向或 的源集合添加string
值,您应该创建一个类,该类包含显示名称的属性和确定当前是否检查项目的另一个属性:tbxFiles.Items
ListBox
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
外观:ListBox
Item
<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);
推荐阅读
- apache-spark - Spark SQL 中的相关子查询
- flutter - 如何在颤动中向警报对话框添加选项卡
- ios - 如何使用 iOS 14+ 的 ScrollViewReader 和 iOS 13 的部署目标
- python - Python - 遍历字典列表
- javascript - 如何减少 Javascript 重复
- android - 如何使用 curl 推送通知
- typescript - 编译时检查 typescript 接口是否具有一个或多个属性
- c# - 无法从程序集“GraphQL,Version=3.0.0.0,Culture=neutral,PublicKeyToken=null”加载类型“GraphQL.Http.IDocumentWriter”
- javascript - 具有固定第一列和固定标题的表格,没有位置粘性
- python - 在二进制 numpy 矩阵中关闭 x% 的 ACTIVE 位,而不是关闭所有位的 x%