如何将用户控件放在文档查看器中?

时间:2011-08-12 01:49:19

标签: c# wpf xaml documentviewer

是否可以将用户控件放在文档查看器中?如果可能的话,会是怎样的?

1 个答案:

答案 0 :(得分:4)

您可以使用以下内容..

修改
添加了Grid,将其Width/Height绑定到FixedPage ActualWidth/ActualHeight以实现居中

<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>

不幸的是Visual Studio 2010设计器在这里被打破,你会收到一条消息,说“属性'页面'不支持'PageContent`类型的值。

这在此报告:WPF FixedDocument object doesn't allow PageContent children

作为一种解决方法,您可以将其加载到

后面的代码中

的Xaml

<DocumentViewer>
    <FixedDocument Loaded="FixedDocument_Loaded"/>
</DocumentViewer>

背后的代码

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);
}