RichtextBox with FlowDocument

Jan 26, 2011 at 7:47 PM

In 3.51 I had setup a BindableRichTextBox with a Document dependency property.  I then used a converter when binding to get the entire flow document XAML string and save it to a database. When I moved the project to .NET 4, this started giving me problems.  Instead of debugging it, I decided to just use the extended toolkit, which wasn’t around when I had done mine originally. Anyway, the difference in this RichTextBox is that it binds to the text of the document… not the actual document.  So, if it’s useful to anyone, below is a text formatter that will let you bind to a XAML string for an entire FlowDocument.  (i.e. "<FlowDocument xmlns=...>...</FlowDocument>")  Good work on the tookit.


using System.IO;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Xml;
using Microsoft.Windows.Controls;

namespace Achc.Prism.Common.Controls.Text
{
    public class FlowTextFormatter : ITextFormatter
    {
        //return string for the entire flow doc
        public string GetText(System.Windows.Documents.FlowDocument document)
        {
            return XamlWriter.Save(document);
        }

        //set the document text from a FlowDocument XAML string
        public void SetText(System.Windows.Documents.FlowDocument document, string text)
        {
            try
            {
                if (!string.IsNullOrEmpty(text)) //only set it if there is a value to set
                {
                    FlowDocument flowDocument;
                    using (StringReader sr = new StringReader(text))
                    {
                        using (XmlReader xr = XmlReader.Create(sr))
                            flowDocument = (FlowDocument)XamlReader.Load(xr);
                    }

                    TextRange trSource = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
                    TextRange trTarget = new TextRange(document.ContentStart, document.ContentEnd);

                    using (MemoryStream ms = new MemoryStream())
                    {
                        trSource.Save(ms, DataFormats.Xaml);
                        trTarget.Load(ms, DataFormats.Xaml);
                    }

                }
            }
            catch
            {
                throw new InvalidDataException("data provided is not in the correct Xaml format.");
            }
        }
    }
}

 

 

 

 

 

 

Jan 26, 2011 at 7:50 PM

Thanks for the contribution.  I am sure this will be helpful to others.  Thanks again for sharing.