I have a main ViewModel which contains a collection of Group ViewModels

public class NavigationVM:ViewModelBase { private ObservableCollection<NavigationGroupViewModel> _groupCollection; public ObservableCollection<NavigationGroupViewModel> GroupCollection { get { return _groupCollection; } set { if (_groupCollection != value) { _groupCollection = value; OnPropertyChanged("GroupCollection"); } } } ... ... } 

In GroupViewModel, I have a DeleteCurrentCommand that is triggered when I click on the ContextMenu item

 private RelayCommand _deleteCurrentCommand; public RelayCommand DeleteCurrentCommand { get { if (_deleteCurrentCommand == null) { _deleteCurrentCommand = new RelayCommand((o) => { MessageBox.Show("Executed command is " + "DeleteCurrentCommand"); }); } return _deleteCurrentCommand; } } 

Now I need to remove this item from the GroupCollection which is in the main ViewModel NavigationVM. What is the best way to do this? Can I subscribe to the DeleteCurrentCommand event from NavigationVM?

    2 answers 2

    I would add a property in the NavigationVM

     NavigationGroupViewModel selectedItem; public NavigationGroupViewModel SelectedItem { get { return selectedItem; } set { if (value != null) if (value.Equals(selectedItem)) return; selectedItem = value; OnPropertyChanged("SelectedItem"); } } 

    in xaml to the element to which your collection is bound would add

     SelectedItem="{Binding SelectedItem}" 

    the delete command would also be transferred to NavigationVM

     private RelayCommand _deleteCurrentCommand; public RelayCommand DeleteCurrentCommand { get { if (_deleteCurrentCommand == null) { _deleteCurrentCommand = new RelayCommand((o) => { SelectedItem.Delete(); GroupCollection.Remove(SelectedItem); OnPropertyChanged("GroupCollection"); }); } return _deleteCurrentCommand; } } 

    Accordingly, the MenuItem in ContextMenu would bind to this command.

      This is essentially not a MVVM issue. You have several objects, how can they contact each other?

      The answer is whatever you like.

      For example, in your case, I would simply pass a link to an external VM to the constructor of NavigationGroupViewModel , and within the implementation of the DeleteCurrentCommand stupidly call a public method, passing myself as an argument.

      • one
        Good evening Vlad, "As you please," I can certainly link them, but I thought there might be a way to subscribe to an event in mainViewModel. I want to do it right - Vadim
      • 2
        @Vadim: Yes, you can, of course. There is no preferred way, make it look right. You can set the event if you want. - VladD