簡體   English   中英

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

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

我在帶有CheckBox WPF應用程序中有一個ListView

我想保存WPF列表中所有Checked行的值...

我怎樣才能做到這一點?

我的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>

您可以將IsChecked屬性直接綁定到ListViewItem的IsSelected 使用RelativeSource綁定到元素。

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

現在,如果您對ListView使用SelectionMode=Multiple ,則可以使用SelectedItems直接提取選中的項目。

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

您應該考慮為您的WPF應用程序使用MVVM模式如果您打算使用MVVM,那么您將需要一個MVVM框架

然后,創建一個表示你的數據綁定對象的類型(例如Book ),然后在你的視圖模型上有一個這種類型的集合(例如ObservableCollection<Book> Books )。

然后,您可以將Book類型的Selected boolean屬性綁定到ListBox ItemTemplate中的CheckBox的IsChecked屬性。

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

您可能不希望使用純粹用於UI( Selected )的屬性來對您的域對象( Book )進行輪詢,因此您可以創建一個BookViewModel類型,該類型會增強Book類型並BookViewModel了視圖的目的BookViewModel對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM