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.
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.
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.
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.
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.
"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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With