Edward Tanguay
Edward Tanguay

Reputation: 193432

What is the easiest way to build a FrameworkElement that has bold and italic markup text?

Is there any more elegant way to do the following?

Basically I need an easy way to programatically build a WrapPanel (or other FrameworkElement) that:

Code:

using System.Windows;
using System.Windows.Controls;

namespace TestAddTextBlock2343
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();

            WrapPanel wp = new WrapPanel();

            wp.AddTextBlock("This is a sentence with ");

            {
                TextBlock tb = wp.AddTextBlockAndReturn("bold text");
                tb.FontWeight = FontWeights.Bold;
            }

            wp.AddTextBlock(" and ");

            {
                TextBlock tb = wp.AddTextBlockAndReturn("italic text");
                tb.FontStyle = FontStyles.Italic;
            }

            wp.AddTextBlock(" in it.");
        }
    }

    public static class XamlHelpers
    {
        public static TextBlock AddTextBlockAndReturn(this WrapPanel wp, string text)
        {
            TextBlock tb = new TextBlock();
            tb.Text = text;
            wp.Children.Add(tb);
            return tb;
        }

        public static void AddTextBlock(this WrapPanel wp, string text)
        {
            TextBlock tb = wp.AddTextBlockAndReturn(text);
        }
    }
}

Upvotes: 0

Views: 376

Answers (1)

Joel B Fant
Joel B Fant

Reputation: 24766

Edit: I discovered in a different answer that the TextBlock also has an Inlines collection to which one can add Runs. Anvaka's answer ingeniously uses an attached property as a sort of converter.


What I think will suit your situation is a FlowDocumentScrollViewer and a FlowDocument. I describe manual creation of one through an IValueConverter a little bit here.

You'll likely use similar helper functions as you've shown in your example, but the FlowDocument is already much like HTML and will handle wrapping effortlessly.

You add Paragraphs to the FlowDocument, you add Runs to the Paragraph, and each Run derives from TextElement so it has a lot of the same properties that TextBlocks do.

FlowDocument doc = new FlowDocument();
Paragraph par = new Paragraph();
doc.Blocks.Add( par );

Run r;
r = new Run( "This is " );
par.Inlines.Add( r );

r = new Run( "bold" );
r.FontWeight = FontWeights.Bold;
par.Inlines.Add( r );

r = new Run( " and this is " );
par.Inlines.Add( r );

r = new Run( "italic" );
r.FontStyle = FontStyles.Italic;
par.Inlines.Add( r );

r = new Run( " text." );
par.Inlines.Add( r );

Also, if the formatting substrings are going to remain restricted to bold/italic tags or some other extremely simple markup, use of Regex.Split() might be the easiest way to determine the separate Runs from a single string. It allows you to split a string into multiple strings but keep your "delimiters".

Upvotes: 4

Related Questions