1

次の関数が WPF MVVM のパラメータのオブジェクト型を取るのはなぜですか?

 public ViewModel()
 {
 SaveCommand2 = new DelegateCommand(SaveCommand_Execute);
 }

 bool SaveCommand_CanExecute(object arg)
 {
        return Model.Name != string.Empty;
 }

デフォルトでは、NULL が渡されるため、関数のパラメーターとして何も渡しません。

何も渡したくない場合は、関数からパラメーターを削除することをお勧めします。しかし、それは許されません。なんで?

4

4 に答える 4

2

これDelegateCommandは、コマンドを作成するための「一般的な」実装です。WPF コマンドには、実行時にコマンドにデータを提供するために使用されるオプションのCommandParameterがあります。DelegateCommandこれがtype の引数を持つ理由objectです。コマンド パラメータ バインディングが使用されている場合、パラメータはこの引数を介して渡されます。

于 2013-12-06T06:32:08.703 に答える
2

delegateこの問題を克服するために、コマンドのカスタム実装を作成できると思います。詳細については、最も一般的なシナリオの Simplify DelegateCommand を参照してください。

于 2013-12-06T06:37:18.647 に答える
1

独自の DelegateCommand を実装する場合は、次のコードに示すように、パラメーターなしのアクションを受け取るコンストラクターを使用できます。

public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
{
  if (execute == null)
    throw new ArgumentNullException("execute", "execute cannot be null");
  if (canExecute == null)
    throw new ArgumentNullException("canExecute", "canExecute cannot be null");

  _execute = execute;
  _canExecute = canExecute;
}

public DelegateCommand(Action<object> execute)
  : this(execute, (o) => true)
{

}

public DelegateCommand(Action execute)
  : this((o) => execute())
{

}

その最後のコンストラクターのオーバーロードでできること

var someCommand = new DelegateCommand(SomeMethod);

ここで、メソッドはパラメーターなしです

于 2013-12-06T15:48:57.003 に答える
1

これを試して、

 public ViewModel()
 {
 SaveCommand2 = new DelegateCommand(new Action(() =>
                {
                  //Your action stuff.
                }), SaveCommand_CanExecute);
 }

 bool SaveCommand_CanExecute()
 {
        return Model.Name != string.Empty;
 }
于 2013-12-06T06:47:36.023 に答える