【问题标题】:Change color and font for some part of text in WPF C#在 WPF C# 中更改部分文本的颜色和字体
【发布时间】:2011-03-26 11:40:28
【问题描述】:

有没有办法更改我想放在 TextBox 或 RichTextBox 上的部分文本的颜色和字体。我正在使用 C# WPF。

例如

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

可变字例如为 Text1 和 Text2 中的其他颜色和字体。是否有可能以及如何做到这一点?

【问题讨论】:

    标签: c# wpf fonts textbox


    【解决方案1】:

    如果您只是想做一些快速着色,最简单的解决方案可能是将 RTB 内容的结尾用作 Range 并对其应用格式。例如:

    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);
    

    如果您正在寻找更高级的解决方案,我建议您阅读this Microsoft Doc about Flow Document,因为它为您提供了极大的文本格式灵活性。

    【讨论】:

    • 对象“rangeOfText1”、“rangeOfWord”和“rangeOfText2”完成后,如何拼接?
    • 谢谢,这是我能找到的最简单的方法!
    【解决方案2】:

    你可以试试这个。

    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 属性。

    【讨论】:

      【解决方案3】:

      【讨论】:

        【解决方案4】:

        我已经创建了自己的class 来操纵Texts 的TextBlockTextBox...

        /// <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");
        

        【讨论】:

          【解决方案5】:

          如果您想先添加一条线,然后再为它的一部分着色,对@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 的字符串被附加到多个函数中,因此如果必须为相应函数中的每个 sn-p 显示颜色,那将非常不方便。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-02-17
            • 2012-03-11
            • 2020-04-04
            • 2014-07-25
            • 1970-01-01
            • 2011-02-18
            相关资源
            最近更新 更多