如何在WPF列表框中获取选中的项目? [英] How to get checked items in a WPF ListBox?
问题描述
我有一个WPF ListBox,其中有多个复选框,但是以什么方式获取已检查的项目列表呢?
I have a WPF ListBox where I have checkboxes, but what's the way to get the list of items that are checked?
列表框是绑定到 Dictionary< T>
的数据.
The ListBox is data binded to a Dictionary<T>
.
这是XAML:
<Window x:Class="WpfApplication.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1"
Height="300"
Width="300">
<Grid Margin="10">
<ListBox ItemsSource="{DynamicResource Nodes}" Grid.IsSharedSizeScope="True" x:Name="MyList">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="Key" />
<ColumnDefinition SharedSizeGroup="Name" />
<ColumnDefinition SharedSizeGroup="Id" />
</Grid.ColumnDefinitions>
<CheckBox Name="NodeItem" Click="OnItemChecked">
<StackPanel Orientation="Horizontal">
<TextBlock Margin="2" Text="{Binding Value.Name}" Grid.Column="1"/>
<TextBlock Margin="2" Text="-" Grid.Column="2"/>
<TextBlock Margin="2" Text="{Binding Value.Id}" Grid.Column="3"/>
</StackPanel>
</CheckBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
推荐答案
乔什·史密斯(Josh Smith)具有文章,该文章应说明您的需求.他正在讨论 TreeView
,但是该原理也将移植到 CheckBox
.
Josh Smith has an article on codeproject that should explain what you need. He is discussing a TreeView
but the principle will port over to the CheckBox
as well.
此处使用 DataTemplate
并将 CheckBox.IsChecked
属性绑定到 ListBoxItem.IsSelected
属性.
There is also a very interesting approach here using a DataTemplate
and Binding the CheckBox.IsChecked
property to the ListBoxItem.IsSelected
property.
如果您不熟悉MVVM, Jason Dolinger 上有一个很好的视频.它逐步引导您完成从使用文件后面的代码到完整的MVVM模式(包括依赖注入和测试)的过程.
If you are new to MVVM, Jason Dolinger has an excellent video on the subject. It steps you through the process moving from using code behind files to a full MVVM pattern including Dependency Injection and Testing.
这篇关于如何在WPF列表框中获取选中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!