3

Do anyone know why being specific with the MVVM Light RelayCommand generic type would cause its canExecute to always resolve to false for the binding? In order to get the correct behavior I had to use an object and then convert it to the desired type.

NOTE: canExecute was simplified to a boolean for testing the block that does not work and is normally a property CanRequestEdit.

Does NOT work:

public ICommand RequestEditCommand {
  get {
    return new RelayCommand<bool>(commandParameter => { RaiseEventEditRequested(this, commandParameter); },
                                  commandParameter => { return true; });
  }
}

Works:

public ICommand RequestEditCommand {
  get {
    return new RelayCommand<object>(commandParameter => { RaiseEventEditRequested(this, Convert.ToBoolean(commandParameter)); },
                                    commandParameter => { return CanRequestEdit; });
  }
}

XAML:

<MenuItem Header="_Edit..." Command="{Binding RequestEditCommand}" CommandParameter="true"/>

You code looks fine, if dd() doesn't stop execution of the controller, then another controller is executing. So double check your routes and controllers.

4

1 に答える 1

2

のコードRelayCommand<T>、具体的には「!!!」でマークした行を見てください。

public bool CanExecute(object parameter)
{
    if (_canExecute == null)
    {
        return true;
    }

    if (_canExecute.IsStatic || _canExecute.IsAlive)
    {
        if (parameter == null
#if NETFX_CORE
            && typeof(T).GetTypeInfo().IsValueType)
#else
            && typeof(T).IsValueType)
#endif
        {
            return _canExecute.Execute(default(T));
        }

        // !!!
        if (parameter == null || parameter is T)
        {
            return (_canExecute.Execute((T)parameter));
        }
    }

    return false;
}

コマンドに渡すパラメーターは文字列「true」であり、boolean ではないため、 is notであり、句が falsetrueであるため、条件は失敗します。つまり、パラメーターの値がコマンドのタイプと一致しない場合は、が返されます。 parameternullisTfalse

ブール値を XAML にハードコードしたい (つまり、サンプルがダミー コードではない) 場合は、この質問を参照してその方法を確認してください。

于 2016-03-21T17:29:20.203 に答える