marc40000
marc40000

Reputation: 3197

How to add a checkbox column to a ListView in WPF and get the state of it

I have a listview with the ItemsSource set to a the result of a linq query like this

listViewPlan.ItemsSource = new ObservableEvents(query);

The values of the result are bound to columns of the listView. Now I'ld like to add another column containing a Checkbox so the user can select some of the items in the listview. So I added this

            <GridViewColumn DisplayMemberBinding="{Binding select}">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <CheckBox Tag="select"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
                <GridViewColumnHeader Click="SortClick" Tag="select" Content="" />
            </GridViewColumn>

This adds a Checkbox column to the listview. But it's not bound to anything from the linq result. So I can't access the current state of the Checkbox with listViewPlan.Items[i] . I also don't want to add a bool to the datatype from the database since the checkbox-states a single user has should not be stored anywhere globally. I could make another class that is similar to the linq class with a bool added for the Checkbox. But then I'ld have to copy all the member variables back and forth. How can I do this?

Upvotes: 1

Views: 1680

Answers (1)

galakt
galakt

Reputation: 1439

You can use multiselect mode in listbox and bind CheckBox.IsChecked to ListViewItem.IsSelected.

<DataTemplate x:Key="ListBoxItemTemplate">
    <CheckBox IsChecked="{Binding Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, 
                                                      AncestorType={x:Type ListViewItem}}, Path=IsSelected}" />
</DataTemplate>

Upvotes: 2

Related Questions