Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass command parameter to method in ViewModel in WPF?

I am trying to pass CommandParameter to the method in my ViewModel. How to do this?

private void Open(object sender) {     if (sender==this.objMainWindow.btnHistory)     {         objMainWindow.Container.Child = objHistory;     }      if (sender == this.objMainWindow.btnNew_Item)     {         objMainWindow.Container.Child = objNewItem;     }      if (sender == this.objMainWindow.btnSide_Effects)     {         objMainWindow.Container.Child = objSideEffect;     } } 

This is my meyhod in ViewModel that I want to pass CommandParameter. I use CommandParameter for button.

like image 677
Mahsa Avatar asked Aug 18 '15 05:08

Mahsa


People also ask

How do you pass a command parameter in WPF MVVM?

Passing a parameter to the CanExecute and Execute methods A parameter can be passed through the "CommandParameter" property. Once the button is clicked the selected address value is passed to the ICommand. Execute method. The CommandParameter is sent to both CanExecute and Execute events.

What is WPF CommandParameter?

Command - gets the command that will be executed when the command source is invoked. CommandParameter - represents a user-defined data value that can be passed to the command when it is executed. CommandTarget - the object on which the command is being executed.

What is MVVM command?

Commands are an implementation of the ICommand interface that is part of the . NET Framework. This interface is used a lot in MVVM applications, but it is useful not only in XAML-based apps.

What does command parameter do?

The CommandParameter property is used to pass specific information to the command when it is executed. The type of the data is defined by the command. Many commands do not expect command parameters; for these commands, any command parameters passed will be ignored.


1 Answers

"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:

<Button Content="Edit"          Command="{Binding EditCommand}"         CommandParameter="{Binding ViewModelItem}" > 

And then this in your view model:

private ViewModelItemType _ViewModelItem; public ViewModelItemType ViewModelItem {     get     {         return this._ViewModelItem;     }     set     {         this._ViewModelItem = value;         RaisePropertyChanged(() => this.ViewModelItem);     } }  public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } } private void OnEdit(ViewModelItemType itemToEdit) {     ... do something here... } 

Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.

like image 193
Mark Feldman Avatar answered Sep 25 '22 03:09

Mark Feldman