wpflistviewselectionchanged

WPF Listview SelectionChanged event


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?


Solution

  • thanks for the responses.

    When I put a breakpoint on the SelectionChanged event, it breaks proceedings there before the screen is fully loaded. You will also see that the first row is 'selected' afterwards on the list. I am not binding to a SelectedIndexValue as you can see in the code. The DataContext for the list is a ReadonlyCollection

    In my SelectionChanged event as you can see I notify other objects to be loaded with data relating to the selected item. I only want this to happen when one is selected but not a default one to be set. I have to of these ListViews representing similar data but on loaded none must have an item selected.

    I have noticed that the default Selected index is set to -1 on the properties window for the Listview. I can even set this is code on the List_Loaded event, but by then the first SelectionChanged has happened already.

    <ListView PreviewMouseDown="ActiveCasesView_MouseDown" x:Name="ActiveCasesView"
                         DataContext="{StaticResource ActiveCasesViewSource}"
                         ItemsSource="{Binding}"
                         ItemTemplate="{StaticResource CasesItemTemplate}"
                         SelectionMode="Single"
                         SelectionChanged="ActiveCasesView_SelectionChanged"
                         ScrollViewer.CanContentScroll="True" 
                         ScrollViewer.VerticalScrollBarVisibility="Auto" >
    </ListView>
    
    private void ActiveCasesView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (mouseClicked)
                if (e.AddedItems.Count > 0)
                    App.Messenger.NotifyColleagues(App.MSG_SELECT_ACTIVE_CASE, ((CaseViewModel)ActiveCasesView.SelectedItem).CaseNumber);
        }
    

    I added the PreviewMouseDown to set an indicator that I have clicked on the listview in the SelectionChanged event. This does help but I'm not convinced that its the best solution.

    Thanks Petrus