文本框文字颜色更改

And*_*rii 5 c# wpf textbox

我已经textbox textbox1并且想要更改文本颜色,但是要更改所有文本的一部分。例如在Visual Studio中从/**/喜欢评论?

我该怎么做?

小智 5

试试这个:

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);
Run Code Online (Sandbox Code Playgroud)

或这个:

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;
Run Code Online (Sandbox Code Playgroud)

来源:

更改 WPF C# 中某些部分文本的颜色和字体

和 MSDN:

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