Berryl
Berryl

Reputation: 12833

Sorting a bound observable collection

I have an MVVM collection that I "know" is reordered in the VM but not showing in it's new order in the view. Given code similar to that below, should I expect the the list to re-display in a new sort without manipulating the CollectionViewSource?

xaml

<Menu Name="_mainMenu" Height="22" >
    <MenuItem Header="Language" 
              ItemsSource="{Binding AvailableCultures}"  >
        <MenuItem.ItemTemplate>
            <DataTemplate>
                <MenuItem IsCheckable="True" 
                          IsChecked="{Binding IsSelected, Mode=TwoWay}"  
                          Header="{Binding DisplayName}"/>
            </DataTemplate>
        </MenuItem.ItemTemplate>
    </MenuItem>
</Menu>

vm

public ObservableCollection<OptionLocalizedViewModel<CultureInfo>> 
                                     AvailableCultures { get; private set; }

private void OnSelectionChange(OptionLocalizedViewModel<CultureInfo> option)
{
    ...
    var sorted = AvailableCultures.OrderBy(x => x.DisplayName);
    AvailableCultures = 
        new ObservableCollection<OptionLocalizedViewModel<CultureInfo>>(sorted);

    NotifyOfPropertyChange(() => AvailableCultures);
}

UPDATE

The order is being changed, but not as expected (and not what the debugger shows the newly sorted ObsCollection to be). I also tried ditching the ObsCollection in favor of binding to an IEnumerable directly with the exact same result.

Does anyone see a pattern that suggests a fix??

1) initial load, looks as it should

enter image description here

2) select Spanish, so should be Espanol first but isn't

enter image description here

3) back to English, but somehow English is last. How did this get flipped?

enter image description here

4) back to Spanish, same as try (2)

enter image description here

Upvotes: 0

Views: 1136

Answers (2)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

This should theoretically work, just be sure INotifyPropertyChanged is actually getting fired correctly as it is necessary when replacing the entire collection with a different one rather than just altering it's contents.

Upvotes: 1

HichemSeeSharp
HichemSeeSharp

Reputation: 3318

Try using ListCollectionView instead :

 ListCollectionView LCV = new ListCollectionView(YourObservableCollection);
 LCV.GroupDescriptions.Add(new PropertyGroupDescription("PropertyName"));
 YourDataBoundProperty = LCV;

You can refer to this article for more detail.

Upvotes: 2

Related Questions