Search code examples
c#wpfmvvmcollectionviewcollectionviewsource

Get index of selected CollectionView item from underlying ObservableCollection source


I have a CollectionView that is bound to the ListView ItemsSource property.

<ListView x:Name="ExampleView" 
          ItemsSource="{Binding CollectionView}" 
          IsSynchronizedWithCurrentItem="True">...</ListView>

Is it possible to get the index of an item from the CollectionViewSource?

CollectionViewSource.GetDefaultView(ObservableCollection);

Below I have illustrated the problem.

When item C from the CollectionView is selected, I want to get an index value of 2 and not 0. Is this possible? enter image description here

Any help is much appreciated. Thanks!


Solution

  • This works for me. It assumes, as your code suggests, that the view you're filtering is the default view for this ObservableCollection.

    var vw = CollectionViewSource.GetDefaultView(MyObservableCollection);
    
    int index = MyObservableCollection.IndexOf(vw.CurrentItem);
    

    Of course you could also bind ListBox.SelectedItem to a SelectedItem property on your viewmodel, and take the index of that also.