WPF Listview SelectionChanged event

Petrus picture Petrus · Sep 2, 2009 · Viewed 47.8k times · Source

I have a ListView binding to an ItemsSource and the SelectionChanged event is firing on the load/databound events? I assume that it is because a 'default' items ie index 0 is selected.

How can I disable this?

Answer

Claudiu Mihaila picture Claudiu Mihaila · Sep 3, 2009

The listView should not fire the SelectionChange if you only set the ItemsSource property. However if you bind the SelectedIndex property to a property of your dataContext object the selection will move to the index that is specified by the binded property.

this doesn't fires the Selector_OnSelectionChanged event when the page loads:

<ListView SelectionChanged="Selector_OnSelectionChanged" 
                  ItemsSource="{Binding Path=Items}"
                  ></ListView>

but this does:

<ListView SelectionChanged="Selector_OnSelectionChanged" 
                  SelectedIndex="{Binding Path=SelectedIndexValue}"
                  ItemsSource="{Binding Path=Items}"
                  ></ListView>

because the SelectedIndex is set to the SelecteIndexValue through binding.

To avoid this and still keep the bindings in your markup set the SelectedIndexValue of your dataContext object to -1 before binding (Before InitializeComponent() is called in your form constructor).

Hope this helps.