开发者

Silverlight formatting text from XML source

I have a large chunk of customer relevant information that I am storing in an XML file.

Each XML element requires some sort of rich text formatting (bold, italics, new line, paragraphs, etc...). I have complete control over the XML file (i.e. I ca开发者_JAVA技巧n wrap the text in other XML elements if required), and it is static (which makes life a bit easier).

What is a good way to store the information in the XML file so that I can load it into my Silverlight page with the correct formatting?

For Example:

I have a string like so:

var str = @"<Run Foreground=""Maroon"" FontFamily=""Courier New"" FontSize=""24"">Courier New 24</Run>";

I cannot just do this:

MyTextBlock.Text = str;

because it prints out literally as the string is defined (no formatting)

However, in XAML, I can define the TextBlock like so:

<TextBlock x:Name="PageDetailsTextBlock">
    <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>
</TextBlock>

And the XAML parser will convert that into the correctly formatted version.

How can do this in C#?


The Xaml parser needed a parent object and a Xaml namespace, but I have created an extension method, for TextBlocks, to do the work for you:

using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;

namespace SilverlightApplication1
{
    static public class TextBlockExtensions
    {
        static public void SetInline(this TextBlock textBlock, string text)
        {
            var str = @"<TextBlock xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"">" + text + "</TextBlock>";
            TextBlock txt = (TextBlock)XamlReader.Load(str);
            List<Inline> inlines = txt.Inlines.ToList();
            txt.Inlines.Clear();
            foreach (var inline in inlines)
            {
                textBlock.Inlines.Add(inline);
            }
        }
    }
}

You can now just say:

MyTextBlock.SetInline(str);

I tested it and it works fine for any normal Xaml text runs. Enjoy.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜