WPF、RichTextBox 在光标位置获取正确文本属性时出现问题
我正在使用 wpf richtextbox 构建一个简单的编辑器。该编辑器具有某种粗体、斜体、下划线等切换按钮,当所选文本或光标处的文本具有适当的属性时,将“按下”这些按钮。我这样做是这样的:
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;
}
}
问题是,当光标位于行尾并且发送例如 ToggleItalic 命令到 RichTextBox 时,我从 SelectedTextRange.GetPropertyValue 返回的值对于光标后面的文本有效而不是我要输入的文本,因此我将返回与命令之前相同的值。但我想要的是,当我发送 ToggleItalic 命令时,结果是当我要输入的字母是斜体时,IsItalic 设置为 true。有谁知道如何解决这个问题?
预先非常感谢,
Liewe
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了一个解决方案,我不应该创建一个新的 TextRange,而只需使用 TextSelection,简而言之,如下所示:
I found a solution, I shoudn't make a new TextRange but just use the TextSelection, in short like this: