使用 WPF MVVM 模式时获取 ListView 中所选项目的索引

Getting index of selected item in a ListView while WPF MVVM pattern is used

我想从 ListView 中获取选定的项目。我的观点是:

<ListView Name="StudentGrid" Grid.Row="1" Margin="1,1,1,1" ItemsSource="{Binding studentList}" SelectedItem="{Binding selectedItem}">

ViewModel 是:

public ObservableCollection<Student> selectedItem { get; set; }
private void DeleteStudent()
{
    ObservableCollection<Student> item = selectedItem;
    if(selectedItem != null)
    {
        int a = item.Count;
    }
}

我想获取所选项目的索引。我该怎么做?

SelectedItem 是绑定集合中的一个对象,因此它是 Student 类型,而不是像列表本身那样的 ObservableCollection<Student> 类型。此外,如果您希望 属性 绑定 two-way,这意味着您还可以更改视图模型中的索引,并且 ListView 将相应地更新所选索引,您必须 implement INotifyPropertyChanged.

public class YourViewModel : INotifyPropertyChanged
{
   private Student _selectedItem;

   // ...other code.

   public Student SelectedItem
   {
      get => _selectedItem;
      set
      {
         if (_selectedItem == value)
            return;

         _selectedItem = value;
         OnPropertyChanged();
      }
   }

   public event PropertyChangedEventHandler PropertyChanged;

   protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
   {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
   }
}

要获取索引,请将 SelectedIndex 属性 绑定到视图模型中 int 类型的 属性。

private int _selectedIndex;

public int SelectedIndex
{
   get => _selectedIndex;
   set
   {
      if (_selectedIndex == value)
         return;

      _selectedIndex = value;
      OnPropertyChanged();
   }
}
<ListView Name="StudentGrid" Grid.Row="1" Margin="1,1,1,1" ItemsSource="{Binding studentList}" SelectedIndex="{Binding SelectedIndex}"/>

您也可以绑定两者或从列表中按索引获取学生。

var student = studentList[SelectedIndex];