private static void TextBox_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter)
return;
var tb = e.OriginalSource as TextBox;
if (tb == null)
return;
//If we pressed enter and if the selected text goes all the way to the end, move our caret position to the end
if (tb.SelectionLength > 0) // && (tb.SelectionStart + tb.SelectionLength == tb.Text.Length))
{
var caretShouldgoTo = tb.SelectionStart + tb.SelectionLength;
tb.SelectionStart = tb.CaretIndex = caretShouldgoTo;
//tb.SelectionStart = tb.CaretIndex = tb.Text.Length;
tb.SelectionLength = 0;
}
if (e.KeyboardDevice.Modifiers == ModifierKeys.Shift)
{
var caretLocation = tb.CaretIndex;
tb.TextChanged -= OnTextChanged;
tb.Text = tb.Text.Insert(tb.CaretIndex, Environment.NewLine);
tb.CaretIndex = tb.SelectionStart = caretLocation + 2;
tb.TextChanged += OnTextChanged;
}
}