0

I've implemented MVVM in WPF and have a ListView as follows:

<ListView DockPanel.Dock="Top" Name="ListViewMain" ItemsSource="{Binding Items}">

... GridView in ListView.View ...

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding OnSelectionChangedCommand}"
                                   CommandParameter="{Binding SelectedIndex, 
                                       ElementName=ListViewMain}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</ListView>

Whenever I change selection by clicking on any item on the ListView, OnSelectionChangedCommand is called with correct SelectedIndex.

But when I change SelectedIndex programatically as follows:

ListViewMain.SelectedIndex = 0;

I get -1 in OnSelectionChangedCommand. How do I get correct SelectedIndex irrespective of selection change method?

Update

The answers in WPF Listview SelectionChanged event don't explain what'll happen when SelectedIndex is set programmatically and how to define the view model's property which is bound do SelectedIndex.

Donotalo
  • 12,748
  • 25
  • 83
  • 121

1 Answers1

0

Finally I've got the solution. The ListView should bind SelectedIndex with a property in view model:

<ListView DockPanel.Dock="Top" Name="ListViewMain" ItemsSource="{Binding Items}" 
          SelectedIndex="{Binding SelectedIndex}">

The ListView shouldn't trigger on SelectionChanged event.

The ListView.DataContext.SelectedIndex (the view model's SelectedIndex) property should call SelectionChanged handler:

public int SelectedIndex
{
    get => _selected_index;
    set
    {
        SetProperty(ref _selected_index, value);
        OnSelectionChangedCommand.Execute(_selected_index);
    }
}
Donotalo
  • 12,748
  • 25
  • 83
  • 121