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:
- wraps correctly
- allows some words to have bold text
- allows some words to have italic text
- allows other formatting, e.g. color, background
- ideal would be some method that converts e.g. "
This is <b>bold</b> and this is <i>italic</i> text.
" into an appropriate FrameworkElement so I can e.g. add it to a StackPanel and display it.
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);
}
}
}