WPF Command MenuItem ViewModel

I am new to WPF and struggling a bit with the script. I have a menu that has menu items. When one of these menu items is pressed, you should call a method that will do something based on the displayed text associated with this menu item. So, for example, the contents of the menu item were "test", so I had to do something with the "test". FYI, this “something” directly affects the collection on the ViewModel.

This is easy to achieve with a click event and without a ViewModel, but I tried to implement MVVM using an explicit ViewModel. So I started to learn commands, but I can’t figure out how to transfer anything from the view back to the command in the ViewModel.

Any suggestions on what I should do here?

thank

+3
source share
2 answers

Given that you have a collection of items controlling the command, I would recommend using something similar to the second Will sentence as follows:

<MenuItem
  Command="{Binding MenuCommand}"
  CommandParameter="{Binding}"
  Header="{Binding DisplayText}" />

On the ViewModel side, you can use DelegateCommand or RelayCommand to connect the handler method. This allows you to check the data of a menu item and do everything you need based on what is in it.

public DelegateCommand<MyMenuObject> MenuCommand { get; private set; }

public ViewModel()
{
    MenuCommand = new DelegateCommand<MyMenuObject>(MenuCommandExecuted);
}

public void MenuCommandExecuted(MyMenuObject parameter)
{
    // do something based on the parameter object
}

MenuCommand ICommand , , , - RelativeSource FindAncestor DataContext (ViewModel) MenuCommand. - .

Prism DelegateCommand

RelayCommand

+5

.

< MenuItem Command = "{Binding MenuCommand}" CommandParameter = "" > </MenuItem>

, , .

+2

Source: https://habr.com/ru/post/1743506/


All Articles