如何在WPF中的ListView中添加复选框列并获取其状态[英] How to add a checkbox column to a ListView in WPF and get the state of it

本文是小编为大家收集整理的关于如何在WPF中的ListView中添加复选框列并获取其状态的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有一个listView,其中设置为linq查询的结果

listViewPlan.ItemsSource = new ObservableEvents(query);

结果的值绑定到ListView的列. 现在,我想添加包含复选框的另一列,以便用户可以在ListView中选择一些项目.所以我添加了这个

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

这在listView中添加了一个复选框.但这与LINQ结果没有任何绑定.因此,我无法使用listViewPlan.items [i]访问复选框的当前状态.我也不想从数据库中添加Bool,因为单个用户已在全球任何地方都存储了一个复选框状态.我可以将另一个类似于LINQ类的类,并为复选框添加一个布尔.但是,然后我必须来回复制所有成员变量.我该怎么做?

推荐答案

您可以在ListBox中使用多选择模式并绑定复选框.

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

本文地址:https://www.itbaoku.cn/post/1557116.html

问题描述

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?

推荐答案

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>