How to change part of text color at RichTextBox

让人想犯罪 __ 提交于 2021-02-10 12:45:33

问题


Good day!

I try to change part of text to red color.

So, i try to use TextBox, but it not works. So, i read, that RichTextBox can do that:i use this question

But i do not know how to append colored text?

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

Ok, i get TextRange, but how to append it to RichTextBox?

Can you tell me how to make some part of text to red color? Thank you!


回答1:


Starting with your example:

TextRange rangeOfText2 = new TextRange(tbScriptCode.Document.ContentEnd,
    tbScriptCode.Document.ContentEnd);

rangeOfText2.Text = "RED !";

rangeOfText2.ApplyPropertyValue(TextElement.ForegroundProperty,Brushes.Red);
rangeOfText2.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);

works for me.

Ok, i get TextRange, but how to append it to RichTextBox?

It has already been added with

new TextRange(tbScriptCode.Document.ContentEnd, tbScriptCode.Document.ContentEnd);

What you also can do (I used this myself lately):

var fd = new FlowDocument();

Paragraph paragraph = new Paragraph();

paragraph.Inlines.Add(new Run("normal text and this is in "));
paragraph.Inlines.Add(new Run("red") { Foreground = Brushes.Red });
paragraph.Inlines.Add(new Run(" and this is blue.") { Foreground = Brushes.Blue });

fd.Blocks.Add(paragraph);

tbScriptCode.Document = fd;


来源:https://stackoverflow.com/questions/28604252/how-to-change-part-of-text-color-at-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!