Capture textbox enter key event using C#

The other day I needed to implement a search function in a WPF program. I wanted the use to be able to enter the criteria and then the enter key to perform the search. I achieved this by adding a KeyDown event to the text box control in the XAML.


And adding the below C# code in the MainWindow.xaml.cs code-behind executed the required search logic.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
     if (e.Key == Key.Return && textBox1.Text != "")
         label1.Content = "You entered: " + textBox1.Text;

This program results in a window like this.


When some text is entered into the text box and the enter key pressed, the entered text will be presented next to the ‘You entered:’ label.

Not a complicated endeavor, but one worth mentioning.

Download the source