web-dev-qa-db-fra.com

Modifier la couleur et la police d'une partie du texte dans WPF C #

Y at-il un moyen de changer la couleur et la police pour une partie du texte que je veux mettre sur TextBox ou RichTextBox. J'utilise C # WPF.

Par exemple

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

La variable Word, par exemple, doit être une autre couleur et une autre police de Texte1 et Texte2. Est-ce possible et comment faire cela?

27
Ivan Tanasijevic

Si vous souhaitez simplement colorer rapidement, utiliser la fin du contenu RTB en tant que plage et y appliquer une mise en forme est peut-être la solution la plus simple, par exemple. 

  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 vous recherchez une solution plus avancée, je vous suggère de lire la page MSDN sur le FlowDocument , car cela vous donne une grande flexibilité pour formater votre texte. 

42
Gimno

Vous pouvez essayer ceci.

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;

Utilisez donc la propriété Document du RichTextBox

15
Angular_Learn

Vous devez utiliser la propriété Document de RichTextBox et y ajouter un Run.

Propriété du document: http://msdn.Microsoft.com/en-us/library/system.windows.controls.richtextbox.document.aspx
Exécutez: http://msdn.Microsoft.com/en-us/library/system.windows.documents.run.aspx

1
publicgk

J'ai créé ma propre class pour manipuler Texts de TextBlock, TextBox...

/// <summary>
/// Class for text manipulation operations
/// </summary>
public class TextManipulation
{
    /// <summary>
    /// Is manipulating a specific string inside of a TextPointer Range (TextBlock, TextBox...)
    /// </summary>
    /// <param name="startPointer">Starting point where to look</param>
    /// <param name="endPointer">Endpoint where to look</param>
    /// <param name="keyword">This is the string you want to manipulate</param>
    /// <param name="fontStyle">The new FontStyle</param>
    /// <param name="fontWeight">The new FontWeight</param>
    /// <param name="foreground">The new foreground</param>
    /// <param name="background">The new background</param>
    /// <param name="fontSize">The new FontSize</param>
    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);
    }

    /// <summary>
    /// Is manipulating a specific string inside of a TextPointer Range (TextBlock, TextBox...)
    /// </summary>
    /// <param name="startPointer">Starting point where to look</param>
    /// <param name="endPointer">Endpoint where to look</param>
    /// <param name="keyword">This is the string you want to manipulate</param>
    /// <param name="fontStyle">The new FontStyle</param>
    /// <param name="fontWeight">The new FontWeight</param>
    /// <param name="foreground">The new foreground</param>
    /// <param name="background">The new background</param>
    /// <param name="fontSize">The new FontSize</param>
    /// <param name="newString">The New String (if you want to replace, can be null)</param>
    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);
        }
    }
}

Usage

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");
0
Dominic Jonas