WPF Listbox selectionchanged MVVM

后端 未结 2 1737
死守一世寂寞
死守一世寂寞 2020-12-28 16:11

I have a list box in my WPF application. I know how to use the selectionchanged event. However I am trying to follow the MVVM design. However I am not sure how to do this.

2条回答
  •  既然无缘
    2020-12-28 17:10

    using SelectionChanged with MVVM is quite simple:

    An approach could be to bind to the SelectedIndex property of the ListBox and in the property setter in the VM, act accordingly as it would be triggered whenever the property changes.

    Example: Here

    In this example whenever the selected index changes, the value of that item is increased by one.

    the main bit is:

    public int SelectedIndex {
      get {
        return _selectedIndex;
      }
    
      set {
        if (_selectedIndex == value) {
          return;
        }
    
        // At this point _selectedIndex is the old selected item's index
    
        _selectedIndex = value;
    
        // At this point _selectedIndex is the new selected item's index
    
        RaisePropertyChanged(() => SelectedIndex);
      }
    }
    

    xaml would just be:

    
    

    Items is the collection of items we bind to.

提交回复
热议问题