How can I put an user control inside a document viewer?
-
17-12-2020 - |
Question
Is it possible put an user control inside a doument viewer? If possible, how will it be that?
La solution
You can use the following..
Edit
Added a Grid
which binds its Width/Height
to the FixedPage
ActualWidth/ActualHeight
to achieve centering
<DocumentViewer>
<FixedDocument>
<PageContent>
<FixedPage HorizontalAlignment="Center">
<Grid Width="{Binding RelativeSource={RelativeSource AncestorType={x:Type FixedPage}},
Path=ActualWidth}"
Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type FixedPage}},
Path=ActualHeight}">
<local:MyUserControl HorizontalAlignment="Center"/>
</Grid>
</FixedPage>
</PageContent>
</FixedDocument>
</DocumentViewer>
Unfortunately the Visual Studio 2010 designer is broken here and you'll get a message saying "Property 'pages' does not support values of type 'PageContent`.
This is reported here: WPF FixedDocument object doesn't allow PageContent children
As a workaround you can load it in code behind
Xaml
<DocumentViewer>
<FixedDocument Loaded="FixedDocument_Loaded"/>
</DocumentViewer>
Code behind
private void FixedDocument_Loaded(object sender, RoutedEventArgs e)
{
FixedDocument fixedDocument = sender as FixedDocument;
MyUserControl myUserControl = new MyUserControl();
myUserControl.HorizontalAlignment = HorizontalAlignment.Center;
myUserControl.VerticalAlignment = VerticalAlignment.Center;
Grid grid = new Grid();
grid.Children.Add(myUserControl);
FixedPage fixedPage = new FixedPage();
fixedPage.Children.Add(grid);
Binding widthBinding = new Binding("ActualWidth");
widthBinding.Source = fixedPage;
Binding heightBinding = new Binding("ActualHeight");
heightBinding.Source = fixedPage;
grid.SetBinding(Grid.WidthProperty, widthBinding);
grid.SetBinding(Grid.HeightProperty, heightBinding);
PageContent pageContent = new PageContent();
(pageContent as IAddChild).AddChild(fixedPage);
fixedDocument.Pages.Add(pageContent);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow