views:

1764

answers:

1

I have a WPF RichTextBox that is dynamically built in a WPF web service. This web service accepts a xaml string that is extracted from the contents of a third-party silverlight RichTextBox control.

<Paragraph TextAlignment=\"Left\"><Run FontFamily=\"Comic Sans MS\" FontSize=\"16\" Foreground=\"#FF0000FF\" FontWeight=\"Bold\" >This text is blue and bold.</Run></Paragraph>

How do I insert this xaml into my WPF RichTextBox? I somewhat understand the concepts of the FlowDocument and Paragraph and Run so I can populate the WPF RichTextBox with text using the code below,

        FlowDocument flowDocument = new FlowDocument();
        Paragraph par = new Paragraph();
        par.FontSize = 16;
        par.FontWeight = FontWeights.Bold;
        par.Inlines.Add(new Run("Paragraph text"));
        flowDocument.Blocks.Add(par);
        rtb.Document = flowDocument;

But what I really don't want to have to parse through the xaml myself to build a paragraph as it can get very complicated. Is there a way to just have the control know how to parse the passed in xaml?

+3  A: 

You can use XamlReader to read your Xaml string and convert it to a control:

string templateString = "<Paragraph xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"  TextAlignment=\"Left\"><Run FontFamily=\"Comic Sans MS\" FontSize=\"16\" Foreground=\"#FF0000FF\" FontWeight=\"Bold\" >This text is blue and bold.</Run></Paragraph>";
StringReader stringReader = new StringReader(templateString);
XmlReader xmlReader = XmlReader.Create(stringReader);
Paragraph template = (Paragraph)XamlReader.Load(xmlReader);

Just make sure you include the following tag in your template:

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

HTH

Arcturus
Excellent answer!
Bob King