簡體   English   中英

WPF RichTextBox:如何在Run(text)的單個句子中添加不同的顏色?

[英]WPF RichTextBox: How to add different colors in a single sentence in Run(text)?

我有一個客戶正在與服務器交談。 服務器可能將緩沖區發送回為“鮑勃:有人在嗎?” 您可以將其視為聊天室。

在第一次出現“:”之前,我想將此詞設為綠色。 ':'右邊的所有內容將保持白色。

我怎樣才能做到這一點? 我發現這不是那么簡單。

這會將傳入的文本消息寫入RichTextBox:

public void WriteLine(string text)
{
    Paragraph para = new Paragraph(); 

    // Buffer output
    para.Inlines.Add(new Run(text));

    // Add block
    txtOutput.Document.Blocks.Add(para);

    // Always keep scrolled to the end
    txtOutput.ScrollToEnd();

    // Clear input field.
    txtInput.Clear();

    // Focus back on the input field.
    txtInput.Focus();
}

我的嘗試:

// Output buffer
para.Inlines.Add(new Run { Text = text, Foreground = Brushes.Green, FontWeight = FontWeights.Bold });

這樣做的問題是整條線都是綠色的。 我需要的是這種格式:

名稱(綠色):輸出(白色)。

請告訴我。 謝謝。

在第一次出現“:”之前,我想將此詞設為綠色。 ':'右邊的所有內容將保持白色。

根據您的需求,您所需要做的就是拆分文本並將兩個Run添加到您的段落中。

檢查以下代碼。

public void WriteLine(string text)
{
    Paragraph para = new Paragraph();

    //Split the content from text

    var content = text.Split(':');

    // Buffer output
    para.Inlines.Add(new Run { Text = content[0] + ": ", Foreground = Brushes.Green, FontWeight = FontWeights.Bold });
    para.Inlines.Add(new Run { Text = content[1], Foreground = Brushes.White, FontWeight = FontWeights.Regular });

    // Add block
    txtOutput.Document.Blocks.Add(para);

    // Always keep scrolled to the end
    txtOutput.ScrollToEnd();

    //// Clear input field.
    //txtInput.Clear();

    //// Focus back on the input field.
    //txtInput.Focus();
}

暫無
暫無

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

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