Cambie el color y la fuente de alguna parte del texto en WPF C #

¿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.

Por ejemplo

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

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

Si solo desea hacer una coloración rápida, usar el final del contenido de la RTB como un rango y aplicarle formato es quizás la solución más simple, por 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 está buscando una solución más avanzada, le sugiero que lea la página de MSDN sobre FlowDocument , ya que esto le brinda una gran flexibilidad para formatear su texto.

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

Entonces use la propiedad Document de RichTextBox

Debe usar la propiedad Documento de RichTextBox y agregarle Ejecutar .

Propiedad del documento: http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.document.aspx
Ejecutar: http://msdn.microsoft.com/en-us/library/system.windows.documents.run.aspx

He creado mi propia class para manipular Text s de TextBlock , TextBox

 ///  /// Class for text manipulation operations ///  public class TextManipulation { ///  /// Is manipulating a specific string inside of a TextPointer Range (TextBlock, TextBox...) ///  /// Starting point where to look /// Endpoint where to look /// This is the string you want to manipulate /// The new FontStyle /// The new FontWeight /// The new foreground /// The new background /// The new FontSize public static void FromTextPointer(TextPointer startPointer, TextPointer endPointer, string keyword, FontStyle fontStyle, FontWeight fontWeight, Brush foreground, Brush background, double fontSize) { FromTextPointer(startPointer, endPointer, keyword, fontStyle, fontWeight, foreground, background, fontSize, null); } ///  /// Is manipulating a specific string inside of a TextPointer Range (TextBlock, TextBox...) ///  /// Starting point where to look /// Endpoint where to look /// This is the string you want to manipulate /// The new FontStyle /// The new FontWeight /// The new foreground /// The new background /// The new FontSize /// The New String (if you want to replace, can be null) public static void FromTextPointer(TextPointer startPointer, TextPointer endPointer, string keyword, FontStyle fontStyle, FontWeight fontWeight, Brush foreground, Brush background, double fontSize, string newString) { if(startPointer == null)throw new ArgumentNullException(nameof(startPointer)); if(endPointer == null)throw new ArgumentNullException(nameof(endPointer)); if(string.IsNullOrEmpty(keyword))throw new ArgumentNullException(keyword); TextRange text = new TextRange(startPointer, endPointer); TextPointer current = text.Start.GetInsertionPosition(LogicalDirection.Forward); while (current != null) { string textInRun = current.GetTextInRun(LogicalDirection.Forward); if (!string.IsNullOrWhiteSpace(textInRun)) { int index = textInRun.IndexOf(keyword); if (index != -1) { TextPointer selectionStart = current.GetPositionAtOffset(index,LogicalDirection.Forward); TextPointer selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length,LogicalDirection.Forward); TextRange selection = new TextRange(selectionStart, selectionEnd); if(!string.IsNullOrEmpty(newString)) selection.Text = newString; selection.ApplyPropertyValue(TextElement.FontSizeProperty, fontSize); selection.ApplyPropertyValue(TextElement.FontStyleProperty, fontStyle); selection.ApplyPropertyValue(TextElement.FontWeightProperty, fontWeight); selection.ApplyPropertyValue(TextElement.ForegroundProperty, foreground); selection.ApplyPropertyValue(TextElement.BackgroundProperty, background); } } current = current.GetNextContextPosition(LogicalDirection.Forward); } } } 

Uso

 TextManipulation.FromTextPointer(_TextBlock.ContentStart, _TextBlock.ContentEnd, "IWantToBeManipulated", NewFontStyle, NewFontWeight, NewForeground, NewBackground, NewFontSize); TextManipulation.FromTextPointer(_TextBlock.ContentStart, _TextBlock.ContentEnd, "IWantToBeManipulated", NewFontStyle, NewFontWeight, NewForeground, NewBackground, NewFontSize, "NewStringIfYouWant");