Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Checked rows values of a ListView in WPF

Tags:

c#

wpf

xaml

I have a ListView in WPF application with a CheckBox.

I want to save the values of all Checked rows in a WPF List ...

How can I achieve this?

My 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>
like image 473
Avinash Singh Avatar asked Oct 20 '12 08:10

Avinash Singh


1 Answers

You can bind the IsChecked property directly to IsSelected of the ListViewItem. Use RelativeSource to bind to the element.

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.

var chapters = new List<Chapter>();
foreach (var item in listViewChapter.SelectedItems)
    users.Add((Chapter)item);
like image 137
McGarnagle Avatar answered Oct 13 '22 20:10

McGarnagle