我正在扩展 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;
}
我要:
不加粗不加粗加粗不加粗
但我得到的是:
不加粗不加粗加粗不加粗
**请注意,输入时它会变成粗体。
如何防止加粗单词后的文本也变成加粗?
不是重复的问题,因为提供的链接的可接受解决方案是针对 WinForms 的,其余的是针对预设文本的。
最佳答案
经过多次测试,我找到了一个简单的解决方案。
CaretPosition = CaretPosition.GetPositionAtOffset(0, LogicalDirection.Forward);
这会将插入符号设置在正确的方向,防止 BOLD 设置在 Run 对象中继续。
if(textPointerEnd.GetNextInsertionPosition(LogicalDirection.Forward) == null)
new Run("", textPointerEnd);
这会将 Run 对象添加到位于 Paragraph 对象末尾的新 Bold 对象的末尾。
关于c# - 在 WPF RichTextBox 中将特定文本设置为粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33559679/