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.
CodePudding user response:
If you don't have an ICommand
defined, you can attach a handler for the UIElement.PreviewKeyUp
event to the TextBox
. Otherwise you will have to define an ICommand
implementation and assign it to the KeyBinding.Command
so that the KeyBinding
can actually execute. Either solution finally executes the same logic to add the linebreak.
You then use the TextBox.AppendText
method to append a linebreak and the TextBox.CaretIndex
property to move the caret to the end of the new line.
MainWindow.xaml
<Window>
<TextBox PreviewKeyUp="TextBox_PreviewKeyUp" />
</Window>
MainWindow.xaml.cs
partial class MainWindow : Window
{
private void TextBox_PreviewKeyUp(object sender, KeyEventArgs e)
{
if (!e.Key.Equals(Key.Enter)
|| !e.KeyboardDevice.Modifiers.HasFlag(ModifierKeys.Shift))
{
return;
}
var textBox = sender as TextBox;
textBox.AppendText(Environment.NewLine);
textBox.CaretIndex = textBox.Text.Length;
}
}