c# - 如何将用户控件放入文档查看器中?

标签 c# wpf xaml documentviewer

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

最佳答案

您可以使用以下..

编辑
添加了一个Grid,将其Width/Height绑定(bind)到FixedPageActualWidth/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 设计器在这里损坏,您将收到一条消息,指出“属性‘pages’不支持‘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);
}

关于c# - 如何将用户控件放入文档查看器中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7034858/

相关文章:

c# - 当应用程序池停止时如何保持 FileSystemWatcher 运行

c# - 如何在我的项目中实现 WCF?

c# - 如何从 ViewModel 适本地在 View 中运行触发器?

c# - IO.Stream 到 WPF 中的图像

c# - 以编程方式安装 Windows 消息队列

c# - 未经检查的 C# block 中的 System.OverflowException

c# - WPF:防止用户离开 TextBox?

c# - Xamarin Forms - 有序列表和 ArgumentOutOfRange

wpf - 在 WPF 的右侧而不是下方弹出的垂直菜单

c# - 动态WPF表单创建方法