2015-11-06 204 views
3

我正在扩展WPF Richtextbox的功能。我想,当我键入它的某些文本变成黑体我能得到一定的文字加粗,但下面的粗体字文本也将成为加粗了在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; 
} 

我想:

NOTBOLDED NOTBOLDED 加粗 NOTBOLDED

,但我得到什么:

NOTBOLDED NOTBOLDED BOLDED NOTBOLDED

**请注意,键入内容时会变成粗体。

如何防止粗体字后的文字变粗体?


不重复的问题,因为所提供的链接接受的解决方案是WinForms和其余为预设的文字。

+0

[使特定文本在文本框中粗体显示]可能的重复(http://stackoverflow.com/questions/6403902/making-specific-text-bolded-in-a-textbox) –

回答

2

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

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

此设置插入符号位置正确,防止BOLD设置在Run对象内继续。

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

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

1

您将需要检测何时不再检测到所需的文本(可能是空间发生时),然后删除粗体值并将其重置为正常。

+0

检测其粗体与否每个角色的性能会很高。有其他选择吗? – SILENT