views:

608

answers:

3

Hi, experts,

I have a .rtf file and want to put it in a richtextbox in silverlight 4. Unfortunately we do not have .rtf property in silverlight 4 richtextbox, we only have .xaml.

So what i did is to create a FlowDocument, than load the .rtf to this FlowDocument, then format it to xaml. then assigned it to richtextbox. But i got a argumentexception.

How to import a .rtf file to silverlight 4 richtextbox?

Thanks!

A: 

I used an ugly solution so far, use a FlowDocument to change the format from rtf to xaml. Then remove the attributes not accepted in SL4 richtext box, codes like below. It works but I hate it. I want to know is there a better solution.

        string xaml = String.Empty;
        FlowDocument doc = new FlowDocument();
        TextRange range = new TextRange(doc.ContentStart, doc.ContentEnd);

        using (MemoryStream ms = new MemoryStream())
        {
            using(StreamWriter sw = new StreamWriter(ms))
            {
                sw.Write(from);
                sw.Flush();
                ms.Seek(0, SeekOrigin.Begin);
                range.Load(ms, DataFormats.Rtf);
            }
        }


        using(MemoryStream ms = new MemoryStream())
        {
            range = new TextRange(doc.ContentStart, doc.ContentEnd);

            range.Save(ms, DataFormats.Xaml);
            ms.Seek(0, SeekOrigin.Begin);
            using (StreamReader sr = new StreamReader(ms))
            {
                xaml = sr.ReadToEnd();
            }
        }

        // remove all attribuites in section and remove attribute margin 

        int start = xaml.IndexOf("<Section");
        int stop = xaml.IndexOf(">") + 1;

        string section = xaml.Substring(start, stop);

        xaml = xaml.Replace(section, "<Section xml:space=\"preserve\" HasTrailingParagraphBreakOnPaste=\"False\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"&gt;");
        xaml = xaml.Replace("Margin=\"0,0,0,0\"", String.Empty);
fresky
Hmm... seeing that Silverlight doesn't support Flowdocument at all this is a bit confusing.
AnthonyWJones
yes, you are right. Silverlight doesn't support Flowdocument, what I did is using FlowDocument in a webservice, and then silverlight can talk to the webservice
fresky
A: 

I suggest you take a look at the free VectorLight Rich Text Box control instead.

AnthonyWJones
i checked the api of vectorlight richtextbox, seems do not surpport rtf directly.
fresky
A: 

I need to do something similar (haven't done it yet ...)

I came across NRTFTRee, a C# RTF parser, which should port to silverlight. http://www.codeproject.com/KB/string/nrtftree.aspx

http://nrtftree.sourceforge.net/examples.html

Doobi