Command
にパラメータを渡す方法を誰か知っていますかCommandHandler
? XAML からハードコードされた文字列の値を渡したいとします。XAML から渡す方法は知っていますが、MVVM コード ビハインドで処理する方法はわかりません。以下のコードは、パラメータを渡す必要がない場合は正常に動作します。
public ICommand AttachmentChecked
{
get
{
return _attachmentChecked ?? (_attachmentChecked = new CommandHandler(() => ExecuteAttachmentChecked(), CanExecuteAttachmentChecked()));
}
}
private void ExecuteAttachmentChecked()
{
}
private bool CanExecuteAttachmentChecked()
{
return true;
}
コマンドハンドラ:
public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;
public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action();
}
}
ベストアンサー1
2つのことを変える必要がある
1.
Commandhandler
受け入れパラメータを変更する
public class CommandHandler : ICommand
{
private Action<object> _action;
private bool _canExecute;
public CommandHandler(Action<object> action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action(parameter);
}
}
2.受け入れる方法を変更します
CommandParameter
:
public ICommand AttachmentChecked
{
get
{
return _attachmentChecked ?? (_attachmentChecked = new CommandHandler(param => ExecuteAttachmentChecked(param), CanExecuteAttachmentChecked()));
}
}
private void ExecuteAttachmentChecked(object param)
{
//param will the value of `CommandParameter` sent from Binding
}
private bool CanExecuteAttachmentChecked()
{
return true;
}