在TextBox中制作特定的文本Boldefaced

Joh*_*ton 16 c# wpf textbox bold

嗨我目前有一个texbox,当用户按下不同的按钮时会向用户输出信息.我想知道是否有办法让我的一些文字加粗,其余的不是.

我尝试过以下方法:

textBox1.FontWeight = FontWeights.UltraBold;
textBox1.Text. = ("Your Name: " );
TextBox1.FontWeight = FontWeights.Regular;
textBox1.Text += (nameVar);
Run Code Online (Sandbox Code Playgroud)

唯一的问题是,使用这种方式会使一切变得大胆或什么都没有.有没有办法做到这一点?我在C#中使用WPF项目

任何意见或建议表示赞赏.谢谢!

编辑:所以现在我想尝试你所有建议的RichText框,但我似乎无法得到任何东西出现在其中:

// 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);
Run Code Online (Sandbox Code Playgroud)

rtb是我在我的wpf中创建的我的richtextbox的名称

谢谢

jwi*_*mer 12

使用RichTextBox,在我为这个问题写的方法下面 - 希望它有所帮助;-)

/// <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
    { }
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*art 11

您将需要使用a RichTextBox来实现此目的:

<RichTextBox Name="richTB">
  <FlowDocument>
    <Paragraph>
      <Run FontWeight="Bold">Your Name:</Run>
      <Run Text="{Binding NameProperty}"/>
    </Paragraph>
  </FlowDocument>
</RichTextBox>
Run Code Online (Sandbox Code Playgroud)

但为什么你想要"你的名字"可以编辑?当然你会想要它作为一个单独的,只读的标签?

<StackPanel Orientation="Horizontal">
    <Label FontWeight="Bold">Your Name:</Label>
    <TextBox Text="{Binding NameProperty}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)


svi*_*ick 11

您可以使用TextBlock其他TextBlocks或Runs内部:

<TextBlock>
    normal text
    <TextBlock FontWeight="Bold">bold text</TextBlock>
    more normal text
    <Run FontWeight="Bold">more bold text</Run>
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

  • @ digz6666通过将它们添加到“ Inlines”集合中。 (2认同)