Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VirtualizingStackPanel + MVVM + multiple selection

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> 

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.

Anybody experienced the same issue, and found a solution (apart from not using a VirtualizingStackPanel)?

like image 840
decasteljau Avatar asked Aug 13 '09 18:08

decasteljau


1 Answers

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}"/> 

in my ViewModel:

private void RemoveSelection(object parameter) {     IList selection = (IList)parameter;     ... } 
like image 67
decasteljau Avatar answered Oct 12 '22 08:10

decasteljau