Search code examples
c#wpfkeyeventargs

Send TextBox KeyEventArgs value before exiting event


I have this:

 private void AssociatedObject_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        if (textBox != null)
        {
            if (e.Key == Key.Return)
            {
                if (e.Key == Key.Enter)
                {
                    textBox.SelectAll();
                    e.Handled = true;
                }
            }
        }
    }

I want to be able to:

  1. Send the input value to its bound variable.
  2. Highlight the input value in TextBox.

This code only highlights the input value but does not send the input value to the bound variable.


Solution

  • This did it:

     private void AssociatedObject_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null)
            {
                if (e.Key == Key.Return)
                {
                    if (e.Key == Key.Enter)
                    {
                        BindingExpression b = textBox.GetBindingExpression(TextBox.TextProperty);
                        if (b != null)
                        {
                            b.UpdateSource();
                        }
    
                        textBox.SelectAll();
                    }
                }
            }
        }