Search code examples
wpfflowdocument

How do I reference my FlowDocument


I've defined a FlowDocument in a WPF control library (Add New Item..., FlowDocument -- is the root element of the file). I intend this to be used in several contexts such as in a user control or on a window, referenced in code for data-binding and export to xps, etc. But I can't figure out how to get a reference to an instance of this document. It doesn't seem to create an object in the compiled assembly.

More specifically, this is my problem

<MyUserControl ........ >
  <FlowDocumentScrollViewer>
    <!-- doesn't work --><namespaceRef:MyFlowDocument /> 
  <FlowDocumentScrollViewer>
</MyUserControl>

Solution

  • The easiest solution is probably to put your FlowDocument inside a Resource Dictionary and then use the x:Key like this

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <FlowDocument x:Key="myFlowDocument" ..>
        </FlowDocument>
    </ResourceDictionary>
    
    <FlowDocumentScrollViewer Name="flowDocumentScrollViewer">
        <StaticResource ResourceKey="myFlowDocument"/>
    </FlowDocumentScrollViewer>
    

    Otherwise you'll have to set the FlowDocument to build action Embedded Resource and lode it in code behind with something like this

    Stream flowDocumentStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("DocumentNameSpace.FlowDocumentName.xaml");
    FlowDocument flowDocument = (FlowDocument)XamlReader.Load(flowDocumentStream);
    flowDocumentScrollViewer.Document = flowDocument;
    

    Update
    I think it might be possible to use an ObjectDataProvider to load the FlowDocument if you want to look into it. Anyway, a ResourceDictionary seems like the easy way out.