简体   繁体   中英

Bold Part of TextBox/RichTextBox in C# Code

There are many examples of how to format the text in a TextBox via xaml code, but I am trying to figure out how to change the code in my .cs file.

//TextBox tb initialized in .xaml code
tb.Text = "<bold>Bold</bold> and normal and <italic>Italic</italic>";

is along the lines of what I am looking for. Is this possible?

The end result would look like:

Bold and normal and Italic

If you decide to use TextBlock you can use the following:

this.myTextBlock.Inlines.Add(new Bold(new Run("Bold")));
this.myTextBlock.Inlines.Add(" and normal and ");
this.myTextBlock.Inlines.Add(new Italic(new Run("italic")));

Otherwise, if you have to use TextBox you can only apply style to whole text, for example using myTextBox.FontWeight .

You can do that for RichTextBox by adding Inlines like this:

Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(new Bold(new Run("Bold")));
paragraph.Inlines.Add(new Run(" and normal"));
paragraph.Inlines.Add(new Italic(new Run(" and Italic")));
richTextBox.Document = new FlowDocument(paragraph);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM