What I want is when for the currently focused textbox to lose focus when the user hits the enter key. The only way I can think to achieve this is by using input bindings in XAML to bind to a command in code that passes down the entire textbox control to the viewmodel. I don't like this approach and was hoping someone had a 'clean' way of approaching this problem.
Asked
Active
Viewed 3,554 times
2 Answers
4
You could create a custom textbox and put this in the controls code:
public partial class CustomTextBox : TextBox
{
public CustomTextBox()
{
InitializeComponent();
}
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if(e.Key == Key.Return)
Keyboard.ClearFocus();
}
}
Then just use your custom textbox wherever you want that particular behaviour.

emybob
- 1,303
- 15
- 22
-
That might actually be better than the way I was planning to do it. Thanks I'll mark it once I get a chance to play around with it. – Thermonuclear Oct 24 '14 at 16:07
-
something to note is the KeyBoard.ClearFocus is for .Net 4.0 so if your using something older then check this thread: http://stackoverflow.com/questions/2914495/wpf-how-to-programmatically-remove-focus-from-a-textbox – emybob Oct 24 '14 at 16:15
2
Quite often you get a password box on login whereby you need to allow the enter key.
<PasswordBox VerticalAlignment="Center" x:Name="txtPassword" Template="{StaticResource PassBoxBaseControlTemplate}" Height="25" BorderBrush="Black" Width="165.031">
<PasswordBox.InputBindings>
<KeyBinding Key="Enter" Command="{Binding ComLoginClickOK}" CommandParameter="{Binding ElementName=txtPassword}"/>
</PasswordBox.InputBindings>
</PasswordBox>

scottsanpedro
- 1,142
- 2
- 12
- 28