Saturday, 5 June 2010

Linking TextBox Key Presses to a DelegateCommand

I needed to detect the <return> key being pressed in a TextBox. The original technique used a KeyPress event and a small event handler in the code-behind. Since we're using MVVM I wanted to replace the event handler with a DelegateCommand.
This .Net 4 only solution binds the DelegateCommand to the Command property of a KeyBinding.

...
KeyReturnCommand = new DelegateCommand(ReturnKeyPressed);
...
public DelegateCommand KeyReturnCommand { get; set; }
private void ReturnKeyPressed(string text)
{
MessageBox.Show(text);
}

<TextBox x:Name="SearchText" Width="100" Height="25">
<TextBox.InputBindings>
<KeyBinding
Command="{Binding KeyReturnCommand}"
CommandParameter="{Binding ElementName=SearchText, Path=Text}"
Key="Enter"/>
</TextBox.InputBindings>
</TextBox>

No comments: