2

私は Mvvmlight を学んでいますが、そのcanExecuteRelayCommand についてかなり混乱しています。

基本的に、私は aButtonと aをPasswordBox持っています。私が望むのは、PasswordBox が空の場合にボタンを無効にすることです。私の解決策は、PasswordBox を CommandParemeter として Button に渡し、canExecute メソッドで PasswordBox を受け取ることです。 null か空かを指定します。最初にコマンドを宣言します。viewCommandviewModel

public ICommand CommandClear { get; private set; }

次に、次のようにインスタンス化しますClass Constructor

CommandConfirm = new RelayCommand<object>((p) => ConfirmExecute(p), (p) => ConfirmCanExecute(p));

最後にcanExecute、以下のようにメソッドを実装します。

private bool ConfirmCanExecute(object parameter)
{
    bool isExecuable = false;
    var passwordBox = parameter as PasswordBox;
    if (!string.IsNullOrEmpty(passwordBox.Password))
        isExecuable = true;
    return isExecuable;
}

System.Reflection.TargetInvocationException未処理の例外が でスローされるため、上記の canExecute メソッドは機能しませんPresentationFramework.dll

そこで、上記のコードを でラップしてみますtry...catch。今回は、魔法のように機能します。

        try
        {
            var passwordBox = parameter as PasswordBox;
            if (!string.IsNullOrEmpty(passwordBox.Password))
                isExecuable = true;
            return isExecuable;
        }
        catch
        {
            return isExecuable;
        }

私はそのような行動についてかなり混乱していcanExecuteます、何かアイデアはありますか?

4

1 に答える 1

3

この行でスタックに p を宣言していますか?ハンドラーが呼び出されたときにまだ存在していますか?

CommandConfirm = new RelayCommand<object>((p) => ConfirmExecute(p), (p) => ConfirmCanExecute(p));

間違ったコマンド バインディングが原因で、null が返されるため、表示されているエラーが発生します。

var passwordBox = parameter as PasswordBox;

次に、ViewModel がこのように View を直接操作するのはなぜですか? Password フィールドを ViewModel に双方向バインドするだけで、ViewModel の CanExecute ハンドラがワンライナーになります。

return !String.IsNullOrEmpty(this.Password);
于 2014-05-08T03:21:19.390 に答える