简体   繁体   English

如何在WPF中获取ListView的Checked行值

[英]How to get Checked rows values of a ListView in WPF

I have a ListView in WPF application with a CheckBox . 我在带有CheckBox WPF应用程序中有一个ListView

I want to save the values of all Checked rows in a WPF List ... 我想保存WPF列表中所有Checked行的值...

How can I achieve this? 我怎样才能做到这一点?

My ListView 我的ListView

<ListView x:Name="listViewChapter" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderThickness="0" SelectionMode="Single" Height="100" Margin="22,234,17,28" Grid.Row="1">
    <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center" >
                    <Label Name="lblChapterID" VerticalAlignment="Center"  Margin="0" Content="{Binding ChapterID}" Visibility="Hidden" />
                    <CheckBox Name="chkChapterTitle" VerticalAlignment="Center" Margin="0,0,0,0" Content="{Binding ChapterTittle}" Checked="chkChapterTitle_Checked" />
                </StackPanel>
            </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

You can bind the IsChecked property directly to IsSelected of the ListViewItem. 您可以将IsChecked属性直接绑定到ListViewItem的IsSelected Use RelativeSource to bind to the element. 使用RelativeSource绑定到元素。

IsChecked="{Binding RelativeSource={RelativeSource AncestorType=ListViewItem},Path=IsSelected}"

Now if you use SelectionMode=Multiple for the ListView, you can pull the checked items directly using SelectedItems . 现在,如果您对ListView使用SelectionMode=Multiple ,则可以使用SelectedItems直接提取选中的项目。

var chapters = new List<Chapter>();
foreach (var item in listViewChapter.SelectedItems)
    users.Add((Chapter)item);

You should consider using the MVVM pattern for your WPF application, and if you're going to use MVVM then you'll want an MVVM framework . 您应该考虑为您的WPF应用程序使用MVVM模式如果您打算使用MVVM,那么您将需要一个MVVM框架

Then, it would be a case of creating a type that represents your databound object (eg Book ), then having a collection of this type on your view model (eg ObservableCollection<Book> Books ). 然后,创建一个表示你的数据绑定对象的类型(例如Book ),然后在你的视图模型上有一个这种类型的集合(例如ObservableCollection<Book> Books )。

You would then bind a Selected boolean property for example on your Book type to the CheckBox's IsChecked property in your ListBox ItemTemplate. 然后,您可以将Book类型的Selected boolean属性绑定到ListBox ItemTemplate中的CheckBox的IsChecked属性。

<CheckBox IsChecked="{Binding Selected}" />

You may not want to polute your domain object ( Book ) with properties purely used for the UI ( Selected ), so you could create a BookViewModel type which augments the Book type and reshapes the object purely for the purposes of the view. 您可能不希望使用纯粹用于UI( Selected )的属性来对您的域对象( Book )进行轮询,因此您可以创建一个BookViewModel类型,该类型会增强Book类型并BookViewModel了视图的目的BookViewModel对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM