I have a WPF ListBox where I have checkboxes, but what's the way to get the list of items that are checked?
The ListBox is data binded to a Dictionary<T>
.
Here is the 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.Colum开发者_如何学运维n="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>
This is usually done through a ViewModel, that is a data structure that exposes to the view (through the DataContext) both the model (your data) and view-specific information, like whether an item is checked or not.
In your example, your Dictionary would not be, say, a Dictionary, but a Dictionary and the PersonViewModel would have a IsChecked property and a Person property pointing to the model.
Otherwise, you have to go and find the checkbox in templates or get to the list box item from the checkbox and this gets complex pretty fast.
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.
There is also a very interesting approach here using a DataTemplate
and Binding the CheckBox.IsChecked
property to the ListBoxItem.IsSelected
property.
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.
精彩评论