Home > Back-end >  SelectedItem returns null in WPF MVVM pattern
SelectedItem returns null in WPF MVVM pattern

Time:03-17

I want to get selected Item from ListView. My view is:

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

The ViewModel is:

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

I want to get index of the selected item. How can I do that?

CodePudding user response:

The SelectedItem is an object in the bound collection, so it is of type Student and not ObservableCollection<Student> like the list itself. Furthermore, if you want the property to be bound two-way, meaning you can also change the index in the view model and the ListView will update the selected index accordingly, you have to 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));
   }
}

To get the index, bind the SelectedIndex property, to a property of type int in your view model.

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}"/>

You could also bind both or get the student by index from your list.

var student = studentList[SelectedIndex];
  • Related