[英]Set specific text to bold in WPF RichTextBox
我正在扩展WPF Richtextbox的功能。 当我输入时,我希望某些文本变为粗体。我能够将某些文本设置为粗体,但粗体字后面的文本也会变为粗体...
下面是我的代码示例:
private bool _Running = false;
void CustomRichTextBox_TextChange(object sender, TextChangedEventArgs e)
{
if(_Running)
return;
_Running = true;
//Logic to see if text detected
//Logic to get TextPointers
//Logic to get TextRange
var boldMe = new TextRange(textPointer1, textPointer2);
//Bold text
boldMe.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
_Running = false;
}
我想要:
NOTBOLDED NOTBOLDED BOLDED NOTBOLDED
但我得到了什么:
NOTBOLDED NOTBOLDED BOLDED NOTBOLDED
**请注意,打字时会变粗。
如何防止粗体字后的文字变粗?
不重复的问题,因为提供的链接的接受解决方案是WinForms,其余的是预设文本。
经过几次测试,我找到了一个简单的解决方案。
CaretPosition = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
这会将插入符设置为正确的方向,从而防止BOLD设置在Run对象中继续。
if(textPointerEnd.GetNextInsertionPosition(LogicalDirection.Forward) == null)
new Run("", textPointerEnd);
这会将Run对象添加到位于Paragraph对象末尾的新Bold对象的末尾。
您将需要检测何时不再检测到所需文本,可能是在出现空格时,然后删除粗体值并将其重置为正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.