Joan Venge
Joan Venge

Reputation: 331032

How to get checked items in a 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?

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

Upvotes: 3

Views: 7123

Answers (2)

VoidDweller
VoidDweller

Reputation: 1856

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.

Upvotes: 2

Timores
Timores

Reputation: 14589

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.

Upvotes: 2

Related Questions