Update ListBox after Change SortDescription in CollectionViewSource

716 views Asked by At

i've a ListBox in my Application, there have a CollectionViewSource as ItemsSource. In the CollectionViewSource is a SortDescription. There will works fine.

But now i have an Event there will Change the SortDescription. That works fine, but the ItemsSource will not refresh. When i try to update the ItemsSource with CollectionViewSource.View.Refresh() than i become an Error because CollectionViewSource.View is null.

Here is the Code that i used:

The CollectionViewSource:

<Grid.Resources>
    <CollectionViewSource Source="{Binding Path=Vertraege}" x:Key="VertraegeSource">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Vertrag.Gruppe.ID" Direction="Ascending" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Grid.Resources>

The ListBox

<ListBox Name="lb_Vertraege" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" ItemTemplate="{StaticResource VertragsListBoxTemplate}" ItemsSource="{Binding Source={StaticResource VertraegeSource}}" ScrollViewer.VerticalScrollBarVisibility="Visible">    

Has anywhere an Idea, what i can do to Update the ItemsSource after Modifying the SortDescription? At the Moment i try this with this C# Code:

ControlTemplate template = this["LeistungserbringerVertraegeTemplate"] as ControlTemplate;
Grid grid = template.LoadContent() as Grid;

CollectionViewSource viewSource = grid.FindResource("VertraegeSource") as CollectionViewSource;

viewSource.SortDescriptions.Clear();
viewSource.SortDescriptions.Add(new System.ComponentModel.SortDescription("VertragsID", System.ComponentModel.ListSortDirection.Ascending));

viewSource.View.Refresh();
1

There are 1 answers

1
deafjeff On

From my experience, Template.LoadContent() is very unusual and not recommended in WPF.

A common way to retrieve the CollectionView is to get it from the ItemsControl that hosts the ItemsSource:

ICollectionView collectionView = CollectionViewSource.GetDefaultView(lb_Vertraege.ItemsSource);

then add your sort descriptions to the Filter delegate:

collectionView.Filter = ... // your sort descriptions