WPF MVVM RelayCommand Action,canExecute,参数

时间:2017-04-12 14:37:24

标签: wpf command relaycommand

我正在使用MVVM,我在一个按钮中定义了一个命令。我想在这个Command中使用一个参数,执行一个动作并证明Canexecute。

我有这个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
    }

使用此按钮

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

在视图模型中。

ModificarLicenciaCommand = new RelayCommand(ModificarLicencia, CanModificarLicencia);

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

private void ModificarLicencia()
{
    // Modificar licencia
}

这是好的,但我想传递一个参数并使用类似的东西:

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>

并在viewModel中:

RelayCommand&LT; SfDataGrid &gt;

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

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

编辑:

有了这个,我在ModificarLicenciaCommand =新的RelayCommand(ModificarLicencia,CanModificarLicencia)中有错误

在CanModificarLicentia ==&gt;错误Argument2:无法从'方法组'转换为'Func'

任何帮助?

2 个答案:

答案 0 :(得分:1)

以下视图模型实现应该有效:

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;
    }
}

答案 1 :(得分:0)

例如,您有一个按钮和一个文本框。 如果文本框的文本不为空,则按钮将仅启用: 在查看中:

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

ViewModel 中:

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

享受您的代码!