textbox text color change

后端 未结 3 1773
鱼传尺愫
鱼传尺愫 2021-01-05 12:58

I have textbox textbox1 and I want to change text color, but in the part of all text. For example from /* to */ like comm

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 13:38

    Try this one:

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

    or this:

    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;
    

    Source:

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

    And MSDN:

    http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.document.aspx

提交回复
热议问题