2011-03-26 86 views
25

有没有办法改变我想放在TextBox或RichTextBox上的某些文本部分的颜色和字体。我正在使用C#WPF。更改WPF C中某些文本部分的颜色和字体C#

例如

richTextBox.AppendText("Text1 " + word + " Text2 "); 

例如可变字是从文本1和文本其他颜色和字体。这是可能的和如何做到这一点?

回答

39

如果你只想做一些快速的着色,使用RTB内容为范围的结束和格式应用于它也许是最简单的解决方案,例如

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

如果你正在寻找一个更先进的解决方案,我建议阅读有关FlowDocument的MSDN页面,因为这让你在格式化你的文字有很大的灵活性。

+0

对象 “rangeOfText1” 后的文档属性 “rangeOfWord” 和 “rangeOfText2” 是完整的,怎么CONCAT呢? – xavendano 2013-04-16 16:49:45

14

你可以试试这个。

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; 

所以使用的RichTextBox

相关问题