1

So I have a simple KeyBinding on an input element that executes a command to kick off some analysis.

<dxe:TextEdit.InputBindings>
    <KeyBinding Key="Enter" Command="{Binding StartAnalysisCommand}" />
</dxe:TextEdit.InputBindings>

There are a few other simple input elements that, when changed, call RaiseCanExecuteChanged on the command. This propagates to the UI button, disabling it and preventing it from executing. But this CanExecute state seems to be entirely ignored by the KeyBinding event, before and after the RaiseCanExecuteChanged is called.

N Jones
  • 1,004
  • 11
  • 18

2 Answers2

2

Tested using a normal WPF TextBox, and it calls CanExecute once you press Enter. Must indeed be an issue in the 3rd party control.

<Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.New" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed"/>
</Window.CommandBindings>

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="ApplicationCommands.New"/>
    </TextBox.InputBindings>
</TextBox>

Edit: Example with a RelayCommand:

public class ViewModel
{
    private RelayCommand _cmd;
    public RelayCommand Cmd {
        get { return _cmd ?? (_cmd = new RelayCommand(Executed, CanExecute)); }
    }

    public void Executed() { throw new NotImplementedException(); }

    public bool CanExecute()
    {
        return true;
    }
}

And the binding with the ViewModel as the context.

<KeyBinding Key="Enter" Command="{Binding Cmd}"/>
Troels Larsen
  • 4,462
  • 2
  • 34
  • 54
  • Note that in my example I am binding directly to a command that implements the ICommand interface. This is different than handling an event. Trying to keep with MVVM and not have to unwrap the binding in an event handler. – N Jones Jun 30 '14 at 20:13
  • There should be no difference in regards to where the Command is implemented (I am still using a Command in example #1). I have updated my example with a RelayCommand binding. If that doesn't work for you, there must be something else wrong. The above code works, and is purely MVVM. Did you use the RelayCommand or are you implementing from scratch? – Troels Larsen Jun 30 '14 at 20:24
1

Okay, I figured out what the problem was. Thanks everyone for helping out--your answers caused me to realize the problem. Turns out it wasn't a matter of the CanExecute being called, but rather the timing of when the binding was updated. CanExecute was being called, but with the previous value of the binding.

I used the solution found on this SO answer to accept the value on Enter and the program now works as I had originally expected.

Community
  • 1
  • 1
N Jones
  • 1,004
  • 11
  • 18