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

查看:981
本文介绍了如何在WPF中将复选框列添加到ListView并获取其状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表视图,其中ItemsSource设置为像这样的linq查询的结果

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

listViewPlan.ItemsSource = new ObservableEvents(query);

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

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>

这会将复选框"列添加到列表视图.但这与linq结果无关.因此,我无法使用listViewPlan.Items [i]访问Checkbox的当前状态.我也不想从数据库的数据类型中添加布尔值,因为复选框状态表明单个用户已经不应该存储在全局任何位置.我可以创建另一个类似于linq的类,并为Checkbox添加bool.但是然后我将不得不来回复制所有成员变量.我该怎么办?

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?

推荐答案

您可以在列表框中使用多选模式,并将CheckBox.IsChecked绑定到ListViewItem.IsSelected.

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>

这篇关于如何在WPF中将复选框列添加到ListView并获取其状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆