在WPF RichTextBox中将特定文本设置为粗体 [英] Set specific text to bold in WPF RichTextBox

查看:572
本文介绍了在WPF RichTextBox中将特定文本设置为粗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在扩展WPF Richtextbox的功能.我希望某些文本在键入时变为粗体.我能够使某些文本变为粗体,但是粗体字后面的文本也将变为粗体...

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...

这里有我的代码示例:

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

但是我得到的是

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?

没有重复的问题,因为提供的链接的公认解决方案是WinForms,其余的是预置文本.

Not duplicate question since the accepted solution for provided link is for WinForms and the rest are for preset text.

推荐答案

经过几次测试,我找到了一个简单的解决方案.

After several tests, I figured out a simple solution.

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

此插入符号的方向正确,防止BOLD设置在Run对象中继续出现.

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

这会将Run对象添加到位于Paragraph对象末尾的新Bold对象的末尾.

This would add a Run object to the end of a new Bold object that was located at the end of the Paragraph object.

这篇关于在WPF RichTextBox中将特定文本设置为粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆