When I press the Enter key, the KeyDown event for the TextBox is not fired if its AcceptsReturn property is set to true. How can I identify when the Enter key is pressed for a TextBox with AcceptsReturn set to true?
If you are looking to completely disable the new line (like @ruffin wants to), subscribe to the PreviewKeyDown event via code behind and set e.Handled to true.
    public MyControl()
    {
        InitializeComponent();
        var keyeventHandler = new KeyEventHandler(TextBox_KeyDown);
        uiText.AddHandler(PreviewKeyDownEvent, keyeventHandler, handledEventsToo: true);
    }
    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if (e.Key == Windows.System.VirtualKey.Enter)
            e.Handled = true;
    }
I tried the below code, and its works for me,
var textBox = new TextBox();
KeyEventHandler keyeventHandler = new KeyEventHandler(textBox_KeyDown);
textBox.AddHandler(TextBox.KeyDownEvent, keyeventHandler, true);
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
*** now Enter Key gets fired eventhough when i set AcceptsReturn as True ***
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With