Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making specific Text Boldefaced in a TextBox

Tags:

c#

wpf

textbox

bold

Hi I currently have a texbox that prints out info to the user when they press diffrent buttons. I was wondering if there was a way to make only some of my text bolded while the rest isnt.

Ive tried the following:

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

Only problem is that using this way will either make everything bold or nothing. Is there a way to do this? Im using WPF project in C#

Any Comments or suggestions are appreciated. Thanks!

EDIT: So now im trying to do the RichText box that you all suggested but I cant seem to get anything to appear in it:

// 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 is the name of my richtextbox i created in my wpf

Thanks

like image 399
Johnston Avatar asked Jun 19 '11 17:06

Johnston


2 Answers

use a RichTextBox, below a method that i have wrote for this problem - hope it helps ;-)

/// <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
    { }
}
like image 139
jwillmer Avatar answered Oct 07 '22 13:10

jwillmer


You can use TextBlock with other TextBlocks or Runs inside:

<TextBlock>
    normal text
    <TextBlock FontWeight="Bold">bold text</TextBlock>
    more normal text
    <Run FontWeight="Bold">more bold text</Run>
</TextBlock>
like image 22
svick Avatar answered Oct 07 '22 12:10

svick