Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ListBox with live shaping/grouping - how to keep selection when item is regrouped?

Tags:

c#

.net

wpf

wpf-4.5

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>
like image 572
Chris Kneller Avatar asked Jun 27 '13 23:06

Chris Kneller


1 Answers

Currently there is no simple solution.

I can see two solutions:

1) Manually stop live updates by user. It is error prone to allow work with jumping data.

Example: Pause button in WCF log viewer from MS.

2) Before you start to update data remember selected item. When update will finish just return selection.

Example: How To Prevent WPF DataGrid From De-Selecting SelectedItem When Items Updated?

like image 51
Artur A Avatar answered Nov 12 '22 05:11

Artur A