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

允我心安 提交于 2019-12-24 16:07:31

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/33756171/how-to-add-a-checkbox-column-to-a-listview-in-wpf-and-get-the-state-of-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!