我正在使用MVVM,我已经在按钮中定义了一个Command。我想在此Command中使用一个参数,执行一个动作并证明是否可以执行。
我有这个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 <SfDataGrid>
ModificarLicenciaCommand = new RelayCommand<SfDataGrid>(ModificarLicencia, CanModificarLicencia);
private void ModificarLicencia(SfDataGrid dataGrid)
{
// Modificar licencia
}
编辑:
有了这个,我在ModificarLicenciaCommand = new RelayCommand(ModificarLicencia,CanModificarLicencia)中出现错误
在CanModificarLicentia ==>中,错误参数2:无法从'方法组'转换为'函数']
有帮助吗?
以下视图模型实现应起作用:
示例,您有一个Button