I'm building a simple editor using the wpf richtextbox. This editor has some sort of toggle buttons for Bold, Italic, Underlined, etc. which are 'pressed' when the selected text or the text at the cursor has the approptiate property. I did it like this:
private TextRange GetSelectedTextRange() {
if(_richTextBox == null) return null;
return new TextRange(_richTextBox.Selection.Start, _richTextBox.Selection.End);
}
private void UpdateIsItalic() {
TextRange selectedTextRange = GetSelectedTextRange();
if(selectedTextRange == null) {
IsItalic = false;
return;
}
object fontStyleObject = selectedTextRange.GetPropertyValue(Run.FontStyleProperty);
if(fontStyleObject is FontStyle) {
FontStyle fontStyle = (FontStyle)fontStyleObject;
IsItalic = (fontStyle == FontStyles.Italic || fontStyle == FontStyles.Oblique);
} else {
IsItalic = false;
}
}
The problem is, when the cursor is at the end of the line and a send for instance the ToggleItalic command to the RichTextBox, the values I get back from SelectedTextRange.GetPropertyValue are valid for the text the cursor is behind and not the text I'm about to type, thus I will get back the same value as before the command. But what I want is that when I send the ToggleItalic command, the result is that IsItalic is set to true when the letter I'm about to type is italic. Has anyone has an idea how to tackle this problem?
Many thanks in advance,
Liewe