私のWPF-Appのメインウィンドウには多くのボタンがあります。 これらのボタンのコマンドは同じインプリメンテーション/機能を持つ必要がありますが、どのボタンが押されたかによって、そのファンクションがアクセスするファイル/パスが変更されます。 ボタンクリックイベントハンドラ(Windowsフォーム)を使用せずにViewModelからクリックされたボタンを検出する方法はありますか?ここでViewModelからどのボタンがクリックされたかを検出するWPF
は、クラスRelayCommandの実装です:ここで
public class RelayCommand : ICommand
{
readonly Func<Boolean> _canExecute;
readonly Action _execute;
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Func<Boolean> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
CommandManager.RequerySuggested += value;
}
remove
{
if (_canExecute != null)
CommandManager.RequerySuggested -= value;
}
}
public Boolean CanExecute(Object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(Object parameter)
{
_execute();
}
}
は、ビューモデルでは、コマンドのコードです:
void DoThisWorkExecute()
{
// if Button1 is clicked...do this
// if Button2 is clicked...do this
}
bool CanDoThisWorkExecute()
{
return true;
}
public ICommand ButtonCommand { get { return new RelayCommand(DoThisWorkExecute, CanDoThisWorkExecute); } }
がどのようにボタンをインスタンス化している参照してください?一般的なMVVMの方法は、CommandとCommandParameterの両方をXAMLにバインドし、パラメータを使用してパスを決定することです。 – PMV
フィールド '_execute'と' _canExecute'の定義は、ちょっと疑わしいです(MVVM light?)。これは 'Action