簡體   English   中英

在WPF RichTextBox中將特定文本設置為粗體

[英]Set specific text to bold in 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 BOLDED NOTBOLDED

但我得到了什么:

NOTBOLDED NOTBOLDED BOLDED NOTBOLDED

**請注意,打字時會變粗。

如何防止粗體字后的文字變粗?


不重復的問題,因為提供的鏈接的接受解決方案是WinForms,其余的是預設文本。

經過幾次測試,我找到了一個簡單的解決方案。

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

這會將插入符設置為正確的方向,從而防止BOLD設置在Run對象中繼續。

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

這會將Run對象添加到位於Paragraph對象末尾的新Bold對象的末尾。

您將需要檢測何時不再檢測到所需文本,可能是在出現空格時,然后刪除粗體值並將其重置為正常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM