簡體   English   中英

更改 WPF C# 中某些部分文本的顏色和字體

[英]Change color and font for some part of text in WPF C#

有沒有辦法更改我想放在 TextBox 或 RichTextBox 上的某些文本部分的顏色和字體。 我正在使用 C# WPF。

例如

 richTextBox.AppendText("Text1 " + word + " Text2 ");

例如,可變字是來自 Text1 和 Text2 的其他顏色和字體。 是否有可能以及如何做到這一點?

如果您只想快速着色,最簡單的解決方案可能是將 RTB 內容的末尾用作范圍並對其應用格式。 例如:

TextRange rangeOfText1 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText1.Text = "Text1 ";
rangeOfText1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText1.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

TextRange rangeOfWord = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfWord.Text = "word ";
rangeOfWord.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
rangeOfWord.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Regular);

TextRange rangeOfText2 = new TextRange(richTextBox.Document.ContentEnd, richTextBox.Document.ContentEnd);
rangeOfText2.Text = "Text2 ";
rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Blue);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

如果您正在尋找更高級的解決方案,我建議您閱讀有關 Flow Document 的 Microsoft Doc ,因為它為您設置文本格式提供了極大的靈活性。

你可以試試這個。

public TestWindow()
{
    InitializeComponent();

    this.paragraph = new Paragraph();
    rich1.Document = new FlowDocument(paragraph);

    var from = "user1";
    var text = "chat message goes here";
    paragraph.Inlines.Add(new Bold(new Run(from + ": "))
    {
        Foreground = Brushes.Red
    });
    paragraph.Inlines.Add(text);
    paragraph.Inlines.Add(new LineBreak());
    this.DataContext = this;
}
private Paragraph paragraph;

使用 RichTextBox 的 Document 屬性。

我已經創建了自己的class來操作TextBlockTextBox Text ......

/// <summary>
/// Class for text manipulation operations
/// </summary>
public class TextManipulation
{
    /// <summary>
    /// Is manipulating a specific string inside of a TextPointer Range (TextBlock, TextBox...)
    /// </summary>
    /// <param name="startPointer">Starting point where to look</param>
    /// <param name="endPointer">Endpoint where to look</param>
    /// <param name="keyword">This is the string you want to manipulate</param>
    /// <param name="fontStyle">The new FontStyle</param>
    /// <param name="fontWeight">The new FontWeight</param>
    /// <param name="foreground">The new foreground</param>
    /// <param name="background">The new background</param>
    /// <param name="fontSize">The new FontSize</param>
    public static void FromTextPointer(TextPointer startPointer, TextPointer endPointer, string keyword, FontStyle fontStyle, FontWeight fontWeight, Brush foreground, Brush background, double fontSize)
    {
        FromTextPointer(startPointer, endPointer, keyword, fontStyle, fontWeight, foreground, background, fontSize, null);
    }

    /// <summary>
    /// Is manipulating a specific string inside of a TextPointer Range (TextBlock, TextBox...)
    /// </summary>
    /// <param name="startPointer">Starting point where to look</param>
    /// <param name="endPointer">Endpoint where to look</param>
    /// <param name="keyword">This is the string you want to manipulate</param>
    /// <param name="fontStyle">The new FontStyle</param>
    /// <param name="fontWeight">The new FontWeight</param>
    /// <param name="foreground">The new foreground</param>
    /// <param name="background">The new background</param>
    /// <param name="fontSize">The new FontSize</param>
    /// <param name="newString">The New String (if you want to replace, can be null)</param>
    public static void FromTextPointer(TextPointer startPointer, TextPointer endPointer, string keyword, FontStyle fontStyle, FontWeight fontWeight, Brush foreground, Brush background, double fontSize, string newString)
    {
        if(startPointer == null)throw new ArgumentNullException(nameof(startPointer));
        if(endPointer == null)throw new ArgumentNullException(nameof(endPointer));
        if(string.IsNullOrEmpty(keyword))throw new ArgumentNullException(keyword);

        TextRange text = new TextRange(startPointer, endPointer);
        TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward);
        while (current != null)
        {
            string textInRun = current.GetTextInRun(LogicalDirection.Forward);
            if (!string.IsNullOrWhiteSpace(textInRun))
            {
                int index = textInRun.IndexOf(keyword);
                if (index != -1)
                {
                    TextPointer selectionStart = current.GetPositionAtOffset(index,LogicalDirection.Forward);
                    TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length,LogicalDirection.Forward);
                    TextRange selection = new TextRange(selectionStart, selectionEnd);

                    if(!string.IsNullOrEmpty(newString))
                        selection.Text = newString;

                    selection.ApplyPropertyValue(TextElement.FontSizeProperty, fontSize);
                    selection.ApplyPropertyValue(TextElement.FontStyleProperty, fontStyle);
                    selection.ApplyPropertyValue(TextElement.FontWeightProperty, fontWeight);
                    selection.ApplyPropertyValue(TextElement.ForegroundProperty, foreground);
                    selection.ApplyPropertyValue(TextElement.BackgroundProperty, background);
                }
            }
            current = current.GetNextContextPosition(LogicalDirection.Forward);
        }
    }
}

用法

TextManipulation.FromTextPointer(_TextBlock.ContentStart, _TextBlock.ContentEnd, "IWantToBeManipulated", NewFontStyle, NewFontWeight, NewForeground, NewBackground, NewFontSize);
TextManipulation.FromTextPointer(_TextBlock.ContentStart, _TextBlock.ContentEnd, "IWantToBeManipulated", NewFontStyle, NewFontWeight, NewForeground, NewBackground, NewFontSize, "NewStringIfYouWant");

您需要使用RichTextBoxDocument屬性並向其添加一個Run

文檔屬性: http : //msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.document.aspx
運行: http : //msdn.microsoft.com/en-us/library/system.windows.documents.run.aspx

如果您想先添加一條線,然后再為它的一部分着色,對@Gimno 的答案稍作改動可能會有所幫助:

TextRange rangeOfLine = new TextRange(rtbTest.Document.ContentEnd, rtbTest.Document.ContentEnd);
rangeOfLine.Text = "This is a long string";
rangeOfLine.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);

TextRange rangeToColor = new TextRange(rtbTest.Document.ContentEnd.GetPositionAtOffset(-5), rtbTest.Document.ContentEnd.GetPositionAtOffset(-2));
rangeToColor.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);

這使您可以先向富文本框添加一行文本,該文本框顏色為黑色。 添加后,根據內容的結尾從 -5 到 -2 的選擇變為紅色。

我添加到 RTB 的字符串被附加到多個函數中,因此如果必須為相應函數中的每個片段顯示顏色,那將非常不方便。

暫無
暫無

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

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