WPF ListBox with real-time shaping / grouping - how to save selection when an item is rearranged?

I have an ObservableCollection in my view model and CollectionViewSource and ListBox in my opinion.

ListBox binds to CollectionViewSource . CollectionViewSource binds to an ObservableCollection , sorting items and grouping them into groups. I have live sorting, and live grouping is enabled using the IsLiveGroupingRequested and IsLiveSortingRequested on the CollectionViewSource , so whenever the base objects of the view model change, they are re-sorted and rearranged into a ListBox . All of this works great.

The problem is the choice. If I select an item in a ListBox and it is re-grouped because the view model object is somehow changed, the item will not be selected when it is moved to a new group.

How to save a selection when a selected item is rearranged?

Here is a simple cropped XAML example showing the problem. If the Category property of one of the objects in AllItems changes, the item will be correctly rearranged due to real-time formatting. However, if this item has been selected, it will be canceled.

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

I searched the internet for solutions, but couldn't find anything. I found this thread , but no solution was sent.

I am pulling my hair out trying to make it work. I would really appreciate any help!

+6
source share
1 answer

There is currently no easy solution.

I see two solutions:

1) Manual stop of live updates by the user. This is an error allowing you to work with transition data.

Example: pause button in a WCF log viewer from MS.

2) Before you start updating the data, remember the selected item. When the update completes only the return.

Example: How to prevent DataGrid WPF from changing when deselecting a selected item when updating items?

+2
source

Source: https://habr.com/ru/post/948282/


All Articles