Formatting text in a TextBlock

前端 未结 6 2126
青春惊慌失措
青春惊慌失措 2020-11-27 11:58

How do I achieve formatting of a text inside a TextBlock control in my WPF application?

e.g.: I would like to have certain words in bold, others in ital

6条回答
  •  再見小時候
    2020-11-27 12:20

    Check out this example from Charles Petzolds Bool Application = Code + markup

    //----------------------------------------------
    // FormatTheText.cs (c) 2006 by Charles Petzold
    //----------------------------------------------
    using System;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Documents;
    
    namespace Petzold.FormatTheText
    {
        class FormatTheText : Window
        {
            [STAThread]
            public static void Main()
            {
                Application app = new Application();
                app.Run(new FormatTheText());
            }
            public FormatTheText()
            {
                Title = "Format the Text";
    
                TextBlock txt = new TextBlock();
                txt.FontSize = 32; // 24 points
                txt.Inlines.Add("This is some ");
                txt.Inlines.Add(new Italic(new Run("italic")));
                txt.Inlines.Add(" text, and this is some ");
                txt.Inlines.Add(new Bold(new Run("bold")));
                txt.Inlines.Add(" text, and let's cap it off with some ");
                txt.Inlines.Add(new Bold(new Italic (new Run("bold italic"))));
                txt.Inlines.Add(" text.");
                txt.TextWrapping = TextWrapping.Wrap;
    
                Content = txt;
            }
        }
    }
    

提交回复
热议问题