Search code examples
wpfmvvmcommandparameter

Process CommandParameter via WPF MVVM


I`m quite begginer at WPF. I have checkBox and I want that every check changes will excecute a command that gets IsChecked parameter and do some action.

I have the next code in my XAML file:

At my viewModel I have the next code:

    private ICommand _addSelectedItemsCommand;
    public ICommand AddSelectedItemsCommand
    {
        get
        {
            if (_addSelectedItemsCommand == null)
            {
                _addSelectedItemsCommand = new RelayCommand(param => this.AddSelectedItems());
            }
            return _addSelectedItemsCommand;
        }
    }


    private void AddSelectedItems()
    {
        Do something...
    }

But for "Do somthing" I need IsChecked parameter, How can i get it?

Thanks


Solution

  • You should use InvokeCommandAction class. You can find it in Expression Blend SDK or you can simply add this NuGet package to your project.

    <CheckBox
      xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
      xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
      <i:Interaction.Triggers>
        <i:EventTrigger EventName="Checked">
          <ei:InvokeCommandAction Command="{Binding AddSelectedItemsCommand}" CommandParameter="..." />
        </i:EventTrigger>
      </i:Interaction.Triggers>
    </CheckBox>