Koscik
Koscik

Reputation: 189

Textbox KeyBinding with AcceptsReturn = true

Basically I have a textbox which will accept return when a checkbox is unchecked and when it's checked I want the textbox to react on KeyBinding I wrote.

<TextBox AcceptsReturn="{Binding IsChecked, ElementName=EnterCheckbox, Converter={StaticResource InvertBooleanConverter}}" >
     <TextBox.InputBindings>
           <KeyBinding Key="Enter" Command="{Binding CmdEnterPressed}"/>
     </TextBox.InputBindings>
</TextBox >

Now in any cases, despite of fact that TextBox.AcceptsReturn is set to True when I press [Return] KeyBinding is firing and I want not to fire it but to go to next line of TB.

Upvotes: 1

Views: 559

Answers (2)

TDaddy Hobz
TDaddy Hobz

Reputation: 464

Have the same problem and the suggested solutions did not fix it. Here is how I worked around it.

  • Leave the first textbox with keybinding as is and create an almost exact copy minus the keybinding and had AcceptReturn set to true
  • Set/Attache the visibility of both (the second inversely) to the Checkbox isChecked property
  • Bind the text to the same property

There should be a better fix, but this did it for me

Upvotes: 0

JleruOHeP
JleruOHeP

Reputation: 10376

You can implement CanExecute for that command like this:

public bool CanExecute(object parameter)
{
    bool acceptReturns = (bool)parameter;
    return !acceptReturns;
}

And in your XAML (as far as CommandParameter is used for both Execute and CanExecute methods):

<KeyBinding Key="Enter" Command="{Binding CmdEnterPressed}" 
                        CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TextBox}}, Path=AcceptsReturn}"/>

Upvotes: 1

Related Questions