问题
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