私はMVVMを使用していますが、私はボタンでコマンドを定義しました。このコマンドでパラメータを使用して、アクションを実行し、Canexecuteかどうかを確認します。WPF MVVM RelayCommandアクション、canExecute、パラメータ
は、私は、このボタン
<Button Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="2"
Style="{StaticResource BotonSelect}" Width="200"
Command="{Binding ModificarLicenciaCommand}" >
<Label Content="Modificar Licencia" />
</Button>
では、ビューモデルにこの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
}
を持っています。
ModificarLicenciaCommand = new RelayCommand(ModificarLicencia, CanModificarLicencia);
private bool CanModificarLicencia()
{
// Comprobar puedo modificar
return true;
}
private void ModificarLicencia()
{
// Modificar licencia
}
これはOKですが、私は、パラメータを渡したいと、このようなものを使用して:
CommandParameter = "{バインディングの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
}
編集:これにより
、私はCanModificarLicentia ==>エラーのargument2でModificarLicenciaCommand =新しいRelayCommand(ModificarLicencia、CanModificarLicencia)
にエラーがあります:に 'メソッドグループ' から変換することはできません'Func'
助けが必要ですか?
だからあなたの問題は何ですか?あなたのコマンドはうまくいくようです。 – mm8
私は投稿を編集してエラーを表示します – user1253414