1
votes

I´m using MVVM, I have defined a Command in a button. I want to use in this Command a parameter, execute an action and proving if Canexecute.

I have this RelayCommand

class RelayCommand<T> : ICommand
    {
        private readonly Action<T> _execute;
        private readonly Func<T, bool> _canExecute;

        /// <summary>
        /// Initializes a new instance of the RelayCommand class that 
        /// can always execute.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <exception cref="ArgumentNullException">If the execute argument is null.</exception>
        public RelayCommand(Action<T> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the RelayCommand class.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        /// <exception cref="ArgumentNullException">If the execute argument is null.</exception>
        public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
        {
            if (execute == null)            
                throw new ArgumentNullException("execute");

            _execute = execute;

            if (canExecute != null)            
                _canExecute = canExecute;            
        }

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            if (_canExecute == null)            
                return true;

            if (parameter == null && typeof(T).IsValueType)
                return _canExecute(default(T));

            return _canExecute((T)parameter);            
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }

        #endregion
    }

With this button

<Button Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"
        Style="{StaticResource BotonSelect}" Width="200"
        Command="{Binding ModificarLicenciaCommand}"                          >
        <Label Content="Modificar Licencia" />
</Button>

And in the View Model.

ModificarLicenciaCommand = new RelayCommand(ModificarLicencia, CanModificarLicencia);

private bool CanModificarLicencia()
{
   // Comprobar puedo modificar                             
   return true;
}

private void ModificarLicencia()
{
    // Modificar licencia
}

This is Ok, but I want to pass a parameter and using something like this:

CommandParameter="{Binding ElementName=DataGridLicencias}"

<Button Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"
    Style="{StaticResource BotonSelect}" Width="200"
    Command="{Binding ModificarLicenciaCommand}"
    CommandParameter="{Binding ., ElementName=DataGridLicencias}" >
    <Label Content="Modificar Licencia" />
</Button>

and in viewModel:

RelayCommand< SfDataGrid >

ModificarLicenciaCommand = new RelayCommand<SfDataGrid>(ModificarLicencia, CanModificarLicencia);

private void ModificarLicencia(SfDataGrid dataGrid)
{
    // Modificar licencia
}

Edit:

With this, I have an error in ModificarLicenciaCommand = new RelayCommand(ModificarLicencia, CanModificarLicencia)

In CanModificarLicentia ==> Error Argument2: cannot convert from 'method group' to 'Func'

Any help?

2
So what is your issue? Your command seems to work just fine. - mm8
I´ve edit the post and show the error - user1253414

2 Answers

2
votes

The following view model implementation should work:

public class ViewModel
{
    public ViewModel()
    {
        ModificarLicenciaCommand = new RelayCommand<SfDataGrid>(ModificarLicencia, CanModificarLicencia);
    }

    private ICommand _modificarLicenciaCommand;
    public ICommand ModificarLicenciaCommand
    {
        get { return _modificarLicenciaCommand; }
        set { _modificarLicenciaCommand = value; }
    }

    private void ModificarLicencia(SfDataGrid dataGrid)
    {
        // Modificar licencia
    }

    private bool CanModificarLicencia(SfDataGrid dataGrid)
    {
        return true;
    }
}
0
votes

Example, you have a Button and a TextBox. The button will only be Enable if the textbox's text is not empty: In View:

<TextBox Name="txtCondition" Width="120" Height="35"/>
<Button Width="120" Height="35" Content="Click me!" Command="{Binding YourICommand}" CommandParameter="{Binding ElementName=txtCondition,Path=Text}">

In ViewModel:

public ICommand YourICommand { get; set; }
YourICommand = new RelayCommand<string>((str) =>
              {
                 MessageBox.Show(str);
              },(str) => { return !string.IsNullOrEmpty(str); });

Enjoy your code !