2011-03-26 67 views
25

¿Hay alguna manera de cambiar el color y la fuente de una parte del texto que quiero poner en TextBox o RichTextBox? Estoy usando C# WPF.Cambiar el color y la fuente de una parte del texto en WPF C#

Por ejemplo

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

palabra variable, por ejemplo, para ser otro color y la fuente de Texto1 y Texto2. ¿Es posible y cómo hacer esto?

Respuesta

39

Si lo que desea es hacer un poco de colorante rápida, utilizando el final del contenido RTB como un rango y aplicar formato a que es tal vez la solución más simple , p.ej

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

Si usted está buscando una solución más avanzada, sugiero la lectura de la página de MSDN acerca de la FlowDocument, ya que esto le da una gran flexibilidad en el formato de su texto.

+0

Después de que el objeto "rangeOfText1", "rangeOfWord" y "rangeOfText2" están completas, cómo concat ellos? – xavendano

14

Puede probar esto.

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; 

a fin de utilizar la propiedad de documento de RichTextBox

Cuestiones relacionadas