Friday, 25 November 2011

How to use FlowDocuments

How to save or load a FlowDocument embedded images

There is a way to save and load a flow document including all embedded images by putting them into a XamlPackage. The following sample shows how to do this:
 
// Save 
var source = new FlowDocument();
var range = new TextRange(source.ContentStart, source.ContentEnd);
using (var stream = File.Create("output.pak"))
{
    range.Save(stream, DataFormats.XamlPackage);
}
 
 
 
// Load
using(var stream = File.OpenRead("output.pak"))
{
    var target = new FlowDocument();
    var range = new TextRange(target.ContentStart, target.ContentEnd);
    range.Load(stream, DataFormats.XamlPackage);    
}
 
 

How to navigate by hyperlinks

If you have a FlowDocument that contains Hyperlinks and you want to perform some action when the user clicks on the link, you can use hook up to the RoutedEvent Hyperlink.RequestNavigateEvent. The following code snippet shows you how to do it:
 
<Window x:Class="HyperlinksInFlowDocument.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <FlowDocumentReader>
            <FlowDocument>
                <Paragraph>
                    <Hyperlink NavigateUri="http://www.google.ch">Google</Hyperlink>
                </Paragraph>
            </FlowDocument>
        </FlowDocumentReader>
    </Grid>
</Window>
 
 
 
public Window1()
{
    InitializeComponent();
    AddHandler(Hyperlink.RequestNavigateEvent, new RoutedEventHandler(OnNavigationRequest));
}
 
public void OnNavigationRequest(object sender, RoutedEventArgs e)
{
    var source = e.OriginalSource as Hyperlink;
    if (source != null) 
        Process.Start(source.NavigateUri.ToString());
}

No comments:

Post a Comment