Capturing the Enter Key in the WPF textbox control
Unlike the visual basic forms textbox control, the WPF textbox control does not have a keypress event. So how do we know when the user has pressed the Enter key while the textbox has focus?
Here's how its done on a standard windows form in vb.net
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress If (e.KeyChar = vbCr) Then CheckedListBox1.Items.Add(TextBox1.Text) TextBox1.Text = "" e.Handled = True End If End Sub
And here's how we do it with a WPF textbox control.We use the PreviewKeyUp Event and the Key property of e the KeyEventArgs, comparing it to Key.Enter.
Private Sub TextBox1_PreviewKeyUp(ByVal sender As Object, ByVal e As System.Windows.Input.KeyEventArgs) Handles TextBox1.PreviewKeyUp If (e.Key = Key.Enter) Then ListBox1.Items.Add(TextBox1.Text) TextBox1.Text = "" e.Handled = True End If End Sub
