VirtualizingStackPanel + MVVM + 多选 [英] VirtualizingStackPanel + MVVM + multiple selection
问题描述
我已经实现了一种类似于这篇文章中描述的选择模式,使用一个用于存储 IsSelected 值的 ViewModel,并通过将 ListViewItem.IsSelected
绑定到 ViewModel IsSelected:
I have implemented a selection pattern similar to the one described in this post using a ViewModel to store the IsSelected value, and by binding the ListViewItem.IsSelected
to the ViewModel IsSelected:
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="IsSelected" Value="{Binding Mode=TwoWay, Path=IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
它一般有效,但我遇到了一个严重的问题.通过使用 VirtualizingStackPanel
作为列表视图中的面板,只会创建可见的 ListViewItem
.如果我使用Ctrl+A"选择所有项目,或者在第一个项目上使用Shift+Ctrl+End"等快捷组合,所有项目都会被选中,但对于不可见的项目,ViewModel 不会得到它的 IsSelected设置为真.这是合乎逻辑的,因为如果未创建 ListViewItem
,则绑定将无法工作.
It works in general, but I encounter a severe problem. By using the a VirtualizingStackPanel
as the panel in the list view, only the visible ListViewItem
are getting created. If I use "Ctrl+A" to select all items, or by using shortcut combination such "Shift+Ctrl+End" on the first item, all items get selected, but for the non visible items, the ViewModel does not get its IsSelected set to true. That is logical, because if the ListViewItem
are not created, the binding can't work.
有人遇到过同样的问题,并找到了解决方案(除了不使用 VirtualizingStackPanel
)?
Anybody experienced the same issue, and found a solution (apart from not using a VirtualizingStackPanel
)?
推荐答案
我在 MVVM 模式中找到了另一种处理选择的方法,它解决了我的问题.不是在视图模型中维护选择,而是从 ListView/ListBox 检索选择,并将其作为参数传递给 Command.全部在 XAML 中完成:
I found another way of handling selection in the MVVM pattern, which solved my issue. Instead of maintaining the selection in the viewmodel, the selection is retrieved from the ListView/ListBox, and passed as a parameter to the Command. All done in XAML:
<ListView
x:Name="_items"
ItemsSource="{Binding Items}" ... />
<Button
Content="Remove Selected"
Command="{Binding RemoveSelectedItemsCommand}"
CommandParameter="{Binding ElementName=_items, Path=SelectedItems}"/>
在我的视图模型中:
private void RemoveSelection(object parameter)
{
IList selection = (IList)parameter;
...
}
这篇关于VirtualizingStackPanel + MVVM + 多选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!