web-dev-qa-db-fra.com

Rendre un texte spécifique en gras dans une zone de texte

Bonjour, j'ai actuellement une boîte aux lettres qui affiche des informations à l'utilisateur lorsqu'il appuie sur différents boutons. Je me demandais s'il y avait un moyen de ne mettre qu'une partie de mon texte en gras alors que le reste ne l'est pas.

J'ai essayé ce qui suit:

textBox1.FontWeight = FontWeights.UltraBold;
textBox1.Text. = ("Your Name: " );
TextBox1.FontWeight = FontWeights.Regular;
textBox1.Text += (nameVar);

Le seul problème, c’est que l’utilisation de cette méthode rendra tout ce qui est en gras ou rien .. .. Y at-il un moyen de le faire? J'utilise un projet WPF en C #

Tous les commentaires ou suggestions sont appréciés . Merci! 

EDIT: Alors maintenant, j'essaie de faire la boîte RichText que vous avez tous suggérée mais je ne peux apparemment rien faire apparaître dans celle-ci:

// Create a simple FlowDocument to serve as the content input for the construtor.
FlowDocument flowDoc = new FlowDocument(new Paragraph(new Run("Simple FlowDocument")));
// After this constructor is called, the new RichTextBox rtb will contain flowDoc.
RichTextBox rtb = new RichTextBox(flowDoc);

rtb est le nom de ma richtextbox créée dans mon wpf

Merci

13
Johnston

utilisez un RichTextBox, ci-dessous une méthode que j'ai écrite pour ce problème - espérons que cela aide ;-)

/// <summary>
/// This method highlights the assigned text with the specified color.
/// </summary>
/// <param name="textToMark">The text to be marked.</param>
/// <param name="color">The new Backgroundcolor.</param>
/// <param name="richTextBox">The RichTextBox.</param>
/// <param name="startIndex">The zero-based starting caracter position.</param>
public static void ChangeTextcolor(string textToMark, Color color, RichTextBox richTextBox, int startIndex)
{
    if (startIndex < 0 || startIndex > textToMark.Length-1) startIndex = 0;

    System.Drawing.Font newFont = new Font("Verdana", 10f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 178, false);
    try
    {               
        foreach (string line in richTextBox.Lines)
        { 
            if (line.Contains(textToMark))
            {
                richTextBox.Select(startIndex, line.Length);
                richTextBox.SelectionBackColor = color;
            }
            startIndex += line.Length +1;
        }
    }
    catch
    { }
}
10
jwillmer

Vous devrez utiliser un RichTextBox pour y parvenir:

<RichTextBox Name="richTB">
  <FlowDocument>
    <Paragraph>
      <Run FontWeight="Bold">Your Name:</Run>
      <Run Text="{Binding NameProperty}"/>
    </Paragraph>
  </FlowDocument>
</RichTextBox>

Mais pourquoi voudriez-vous que votre nom soit modifiable? Vous voudriez sûrement que ce soit comme une étiquette séparée en lecture seule?

<StackPanel Orientation="Horizontal">
    <Label FontWeight="Bold">Your Name:</Label>
    <TextBox Text="{Binding NameProperty}"/>
</StackPanel>
11
Kent Boogaart

Vous pouvez utiliser TextBlock avec d'autres TextBlocks ou Runs à l'intérieur:

<TextBlock>
    normal text
    <TextBlock FontWeight="Bold">bold text</TextBlock>
    more normal text
    <Run FontWeight="Bold">more bold text</Run>
</TextBlock>
10
svick

Un TextBox normal ne prend en charge que le réglage tout ou rien de telles propriétés stylistiques. Vous voudrez peut-être examiner RichTextBox , mais vous ne pouvez pas simplement spécifier un ensemble de valeurs pour une propriété Text de la façon que vous avez essayée. Vous devrez travailler avec un FlowDocument pour construire votre corps de texte à l'aide de la propriété Document .

Pour un aperçu de l'utilisation de FlowDocument et de quelques exemples, donnez-le à lire .

3
Grant Thomas

Jetez un coup d'œil au contrôle RichTextBox . Il fonctionne de la même manière que le TextBox, mais permet davantage de personnalisation et prend, bien sûr, Rich Text qui permet un formatage partiel.

1
PedroC88

la réponse de jwillmer comportait quelques erreurs pour moi. Celles-ci ont été résolues en ajoutant:

using System.Drawing;

puis en modifiant les entrées pour:

public static void ChangeTextcolor(string textToMark, System.Drawing.Color color, System.Windows.Forms.RichTextBox richTextBox, int startIndex)

C'était parce que mon code cherchait System.Windows.Controls.RichTextbox et non Windows.Forums.RichTextBox. Et System.Windows.Media.Color pas System.Drawing.Color

0
Kieron

Prenant l’excellent exemple de jwillmer, j’ai fait quelques ajustements car il colorait pour moi toute la ligne d’erreur:

    public static void ChangeTextcolor(string textToMark, Color color, RichTextBox richTextBox)
    {
        int startIndex = 0;

        string text = richTextBox.Text;
        startIndex = text.IndexOf(textToMark);

        System.Drawing.Font newFont = new Font("Verdana", 10f, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 178, false);

        try
        {
            foreach (string line in richTextBox.Lines)
            {
                if (line.Contains(textToMark))
                {
                    richTextBox.Select(startIndex, textToMark.Length);
                    richTextBox.SelectionColor = color;
                    richTextBox.SelectionFont = newFont;
                }
            }
        }
        catch{ }
    }

En outre, j'ai ajouté des balises uniques avant et après le texte à colorier pour obtenir le texte, puis les a supprimées.

0
Zath .