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

编程入门 行业动态 更新时间:2024-10-11 17:26:17
本文介绍了在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中将特定文本设置为粗体

本文发布于:2023-11-10 14:34:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575642.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:设置为   中将   粗体   文本   WPF

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!