So I was messing with fixed documents and I came across the same problem. and I think this is maybe even a cleaner workaround than what others have suggested.
So basically you should create a custom class derived from FixedDocument
as hillin suggested, and add a property to get FixedDocument
from this object's PageContents
. but since these pages are now visual children of another object you should make a copy of them using XmlReader and XmlWriter classes.
[ContentProperty("Pages")]
public class CustomFixedDocument : FixedDocument
{
private ObservableCollection<PageContent> _pages;
public CustomFixedDocument()
{
this.Pages = new ObservableCollection<PageContent>();
}
public FixedDocument FixedDocument
{
get
{
var document = new FixedDocument();
foreach (var p in Pages)
{
var copy = XamlReader.Parse(XamlWriter.Save(p)) as PageContent;
document.Pages.Add(copy);
}
return document;
}
}
public new ObservableCollection<PageContent> Pages
{
get => _pages;
set
{
_pages = value;
foreach (var page in _pages)
{
base.Pages.Add(page);
}
_pages.CollectionChanged += (o, e) =>
{
if (e.NewItems != null)
{
foreach (PageContent page in e.NewItems)
{
base.Pages.Add(page);
}
}
};
}
}
}
now in the xaml you could easily create a CustomFixedDocument
StaticResource and bind your DocumentViewer
to the 'FixedDocument' property of it.
<Window x:Class="MyProject.DocumentWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
Title="DocumentWindow" Height="450" Width="800" Loaded="Window_Loaded">
<Window.Resources>
<local:CustomFixedDocument x:Key="Report">
<PageContent>
<FixedPage Width="793.76" Height="1122.56">
<TextBlock Margin="50" Text="Page 1"/>
</FixedPage>
</PageContent>
<PageContent>
<FixedPage Width="793.76" Height="1122.56">
<TextBlock Margin="50" Text="Page 2"/>
</FixedPage>
</PageContent>
</local:CustomFixedDocument>
</Window.Resources>
<Grid>
<DocumentViewer x:Name="viewer" Document="{Binding Source={StaticResource Report}, Path=FixedDocument}"/>
</Grid>
Now both issues have been addressed. there is live design time preview with no compile errors and the output could be printed.