Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable CollectionViewSource

I am trying to set up a ListBox that gets it's data from a CollectionViewSource. What I want to happen is that when I update the underlying data source the ListBox also updates. My Xaml looks like this...

<Window.Resources>
    <ObjectDataProvider x:Key="AppTests" ObjectType="{x:Type Application:AppTestProvider}" MethodName="GetAppTests" />
    <CollectionViewSource x:Key="cvs" Source="{StaticResource AppTests}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Priority" Direction="Ascending" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>
</Window.Resources>

<Grid>
    <ListBox x:Name="TestList" ItemsSource="{Binding Source={StaticResource cvs}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding TestName}" />                    
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

This displays the data fine but if I change the underlying data then the changes don't appear on the grid until I call the cvs.View.Refresh() method in the code behind.

How can I make this "observable" so the changes happen automatically?

Note: The reason for using the CVS was to provide sorting to the list based on a property in the underlying objects.

like image 583
Remotec Avatar asked Mar 24 '23 00:03

Remotec


1 Answers

To see changes, made to the collection itself (e.g. adding and removing items), the collection should implement INotifyCollectionChanged (ObservableCollection is the base implementation of this interface). To see changes, made to items in the collection (e.g. modifying a specific property on specific item), your item object should implement INotifyPropertyChanged.

CollectionViewSource is a layer between UI and actual collection, which provides some additional control over how the collection is displayed (sorting, filtering, grouping, etc.). It only passes notifications to UI if underlying data supports notifications (by implementing interfaces mentioned above).

like image 185
Nikita B Avatar answered Apr 03 '23 05:04

Nikita B