Это легко решить, если вы обрабатываете OnTextInput
.
protected override void OnTextInput(TextCompositionEventArgs e)
{
TextRange range = new TextRange(this.Selection.Start, this.Selection.End);
// Doesn't matter whether the selection is empty or not, it should be
// replaced with something new, and with the right formatting
range.Text = e.Text;
// Now nothing else would get affected...
range.ApplyPropertyValue(TextElement.FontFamilyProperty, value);
this.CaretPosition = range.End;
e.Handled = true; // You might not need this line :)
}
EDIT:
Установка CaretPosition
в конец TextRange
может привести к неправильному выравниванию Caret
. Мой RichTextBox
имеет много BaselineAlignment
настроек, так что, возможно, именно это и послужило причиной моего. Но, если вы когда-либо испытывали забавные Caret
скачки или падения, попробуйте проверить, находится ли Caret
в конце Paragraph
каждый раз, прежде чем правильно установить CaretPosition
. Примерно так будет работать:
TextRange test = new TextRange(range.End, range.End.Paragraph.ContentEnd);
bool IsAtEnd = test.IsEmpty || String.IsNullOrEmpty(test.Text) || test.Text == "\r\n";
// Now we know whether the Caret is still in the middle of the text or not
// This part corrects the Caret glitch! :)
if (!IsAtEnd)
this.CaretPosition = range.End;
else
this.CaretPosition = range.Start.GetNextContextPosition(LogicalDirection.Forward);
Я знаю, что мой ответ опоздал и все, но надеюсь, что я помог кому-то еще. Ура!