Set specific text to bold in WPF RichTextBox

我的未来我决定 提交于 2019-12-10 13:45:50

问题


I am extending the functionality of a 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

but what I get:

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.


回答1:


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.

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.




回答2:


You will need to detect when your required text is no longer detected, probably if a space occurs, then remove the bolding value and reset it back to normal.



来源:https://stackoverflow.com/questions/33559679/set-specific-text-to-bold-in-wpf-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!