Music. Coding. Gaming. Life.

Databinding to a XAML FlowDocument

Posted Tuesday, December 11th, 2007 5:25:00 am
I couldn't find a full example of this, I had to put bits and pieces together before I got this working.

Let's say you have a datasource, and in that datasource, one of the datamembers is a string that contains some FlowDocument XAML. For example:

<Section xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Paragraph>This is a test.</Paragraph>
</Section>

Unfortunately, there's no way to directly bind a string to a FlowDocument object. However, XAML databinding allows the use of custom converters that allows you to take that string and convert it to whatever you like. To do this, create a class:

Namespace Converters
 
    <ValueConversion(GetType(Object), GetType(FlowDocument))> Public Class FlowDocumentConverter
        Implements IValueConverter
 
        Public Function Convert(ByVal objValue As Object, ByVal tTarget As Type, ByVal objParam As Object, _
                    ByVal ciCulture As CultureInfo) As Object Implements IValueConverter.Convert
            Using msDocument As New MemoryStream((New ASCIIEncoding).GetBytes(CStr(objValue)))
                Dim fdDocument As New FlowDocument()
                Dim trDocument As New TextRange(fdDocument.ContentStart, fdDocument.ContentEnd)
                trDocument.Load(msDocument, DataFormats.Xaml)
                trDocument = Nothing
                Return fdDocument
            End Using
        End Function
 
        Public Function ConvertBack(ByVal objValue As Object, ByVal tTarget As Type, ByVal objParam As Object, _
                    ByVal ciCulture As CultureInfo) As Object Implements IValueConverter.ConvertBack
            Return Nothing 'Not interested in converting back from a FlowDocument to a String
        End Function
 
    End Class
 
End Namespace

Now add your xmlns to the page/usercontrol/window/whatever...

<Page ... xmlns:converters="clr-namespace:Converters" ... >

Create yourself some resources...

<Page.Resources>
    <converter:FlowDocumentConverter x:Key="FlowDocumentConverter" />
</Page.Resources>

And bind like so...

<FlowDocumentScrollViewer Document="{Binding PropertyName, Converter={StaticResource FlowDocumentConverter}}" />

Just replace "PropertyName" with the name of the property or column that has the XAML FlowDocument string you wish to use.

It's a little counter-intuitive, it would be nice if you could just Document="{Binding PropertyName}" and be done with it, converting it to a FlowDocument on the fly... but the solution here is easy enough.

Comments

Loading...
roncli.com Media Player