I have an ObservableCollection
in my view-model, and a CollectionViewSource
and ListBox
in my view.
The ListBox
binds to the CollectionViewSource
. The CollectionViewSource
binds to the ObservableCollection
, sorting the items and arranging them into groups. I have live sorting and live grouping enabled via the IsLiveGroupingRequested
and IsLiveSortingRequested
properties on the CollectionViewSource
, so whenever the underlying view-model objects change, they are re-sorted and re-grouped in the ListBox
. This all works fine.
The problem has to do with the selection. If I select an item in the ListBox
, and it is then re-grouped due to the view-model object being changed in some way, the item will be un-selected when it is moved to the new group.
How can I keep the selection when the selected item is re-grouped?
Here is a simple trimmed-down XAML example showing the problem. If the Category property of one of the objects in AllItems changes, the item will be correctly re-grouped thanks to live shaping. However, if that item was selected, it will become unselected.
<Grid>
<Grid.Resources>
<CollectionViewSource x:Key="MyItems" Source="{Binding AllItems}" IsLiveGroupingRequested="True" IsLiveSortingRequested="True">
<CollectionViewSource.SortDescriptions>
<componentModel:SortDescription PropertyName="Category" />
<componentModel:SortDescription PropertyName="Name" />
</CollectionViewSource.SortDescriptions>
<CollectionViewSource.GroupDescriptions>
<PropertyGroupDescription PropertyName="Category" />
</CollectionViewSource.GroupDescriptions>
</CollectionViewSource>
</Grid.Resources>
<ListBox ItemsSource="{Binding Source={StaticResource MyItems}}">
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" />
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListBox.GroupStyle>
</ListBox>
</Grid>