SelectedItem set to first item with CollectionViewSource
Asked Answered
S

1

8

I have a view databound through mvvm light to a viewmodel in my WP7 project. The view contains a Listbox with following settings:

<ListBox x:Name="StationList"
    ItemsSource="{Binding StationList}"
    SelectedItem="{Binding SelectedStation, Mode=TwoWay}"
    >

The StationList is a ObservableCollection.

Now when the view gets loaded, everything looks great! The list is shown and NO item is selected!

But when I change the XAML to:

<ListBox x:Name="StationList"
            ItemsSource="{Binding Source={StaticResource StationListSorted}}"
            SelectedItem="{Binding SelectedStation, Mode=TwoWay}"
            >

With the StationListSorted being a simple one property sort on the StationList as a CollectionViewSource. Now things turn ugly!! The same view is loaded with the same items in the listbox, but now correctly sorted, BUT the first item is selected and the selectedItem property is set!!

How can I sort a ListBox with a CollectionViewSource WITHOUT it auto selecting my first item?

Sculpin answered 30/7, 2011 at 20:36 Comment(0)
R
19

On your listbox, try setting IsSynchronizedWithCurrentItem and see which value (either true or false) produces the desired effect.

Retrad answered 30/7, 2011 at 20:57 Comment(3)
But WHY?! Why is this the answer?Merow
I don't know if this is the right answer, but it seems that the default CollectionView is created with no current item selected but after applying a sort, a current item is selected. By telling data bound controls no not synchronize to the current item, they're not automatically updated with the CollectionView's current item value.Retrad
It's a poorly named property. It really means whether or not to allow the collectionview to set the selected item/index/etc. Otherwise, the selection will only be changed by the control or the binding source.Potent

© 2022 - 2024 — McMap. All rights reserved.