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

后端 未结 4 1100
孤城傲影
孤城傲影 2020-11-27 18:25

Is there a way to change color and font for some part of text which I want to put on TextBox or RichTextBox. I am using C# WPF.

For example

 richText         


        
4条回答
  •  一向
    一向 (楼主)
    2020-11-27 19:00

    If you just want to do some quick coloring , using the end of the RTB content as a Range and apply formatting to it is maybe the simplest solution, e.g.

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

    If you are looking for a more advanced solution, I suggest reading the MSDN page about the FlowDocument, as this gives you a great flexibility in formatting your text.

提交回复
热议问题