Search code examples
wpfxamltextboxnewline

XAML - How can I use a KeyBinding command to go to a new line in the textbox?


I am simply trying to move to a new line when Return + Shift are pressed.

I got this much from a previous post on here:

<TextBox.InputBindings>
                <KeyBinding Key="Return" Modifiers="Shift" Command=" " />
</TextBox.InputBindings>

But I cannot find anywhere that explains how to accomplish the move to a new line within the textbox.

I cannot use the: AcceptsReturn="True" as I want return to trigger a button.


Solution

  • I found a nice way to do it without using an ICommand.

    Simply added this PreviewKeyDown event onto the control in xaml:

    PreviewKeyDown="MessageText_PreviewKeyDown"
    

    And this is the C# behind:

    private void MessageText_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            // Get the textbox
            var textbox = sender as TextBox;
    
            // Check if we have pressed enter
            if (e.Key == Key.Enter && Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                // Add a new line where cursor is
                var index = textbox.CaretIndex;
    
                // Insert a new line
                textbox.Text = textbox.Text.Insert(index, Environment.NewLine);
    
                // Shift the caret forward to the newline
                textbox.CaretIndex = index + Environment.NewLine.Length;
    
                // Mark this key as handled by us
                e.Handled = true;
            }
        }