简体   繁体   English

在WPF RichTextBox中将特定文本设置为粗体

[英]Set specific text to bold in WPF RichTextBox

I am extending the functionality of a WPF Richtextbox. 我正在扩展WPF Richtextbox的功能。 I want certain text to become bold when I type it in. I was able to get certain text to bold but the text following the bolded word would also become bolded... 当我输入时,我希望某些文本变为粗体。我能够将某些文本设置为粗体,但粗体字后面的文本也会变为粗体...

Heres a sample of my code: 下面是我的代码示例:

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;
}

I want: 我想要:

NOTBOLDED NOTBOLDED BOLDED NOTBOLDED NOTBOLDED NOTBOLDED BOLDED NOTBOLDED

but what I get: 但我得到了什么:

NOTBOLDED NOTBOLDED BOLDED NOTBOLDED NOTBOLDED NOTBOLDED BOLDED NOTBOLDED

**Please note that it becomes bolded while typing. **请注意,打字时会变粗。

How do I prevent the text after a bolded word from also becoming bolded? 如何防止粗体字后的文字变粗?


Not duplicate question since the accepted solution for provided link is for WinForms and the rest are for preset text. 不重复的问题,因为提供的链接的接受解决方案是WinForms,其余的是预设文本。

After several tests, I figured out a simple solution. 经过几次测试,我找到了一个简单的解决方案。

CaretPosition = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);

This set caret in the right orientation, preventing the BOLD setting from continuing within the Run object. 这会将插入符设置为正确的方向,从而防止BOLD设置在Run对象中继续。

if(textPointerEnd.GetNextInsertionPosition(LogicalDirection.Forward) == null)
    new Run("", textPointerEnd);

This would add a Run object to the end of a new Bold object that was located at the end of the Paragraph object. 这会将Run对象添加到位于Paragraph对象末尾的新Bold对象的末尾。

您将需要检测何时不再检测到所需文本,可能是在出现空格时,然后删除粗体值并将其重置为正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM