将页面加载到ContentControl中

时间:2013-04-26 17:18:56

标签: xaml windows-8 windows-runtime winrt-xaml contentcontrol

我有一个ContentControl,我想加载页面 myPage2 。此页面中的我的XAML代码如下所示:

<Page x:Class="ExampleApp.myPage2">
    <Grid x:Name="Content" Height="651" Width="941" Background="White">
        ...
        ...
    </Grid>
</Page>

我知道我可以使用此代码从页面加载资源:

protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
    var contentControl = (ContentControl)container;
    return (DataTemplate) contentControl.Resources[templateKey];
}

我现在的问题是我无法使用此代码加载上述页面。我必须写这个:

<Page x:Class="ExampleApp.myPage2">
    <Page.Resources> 
        <DataTemplate x:Key="Test">       
            <Grid x:Name="Content" Height="651" Width="941" Background="White">
                ...
                ...
            </Grid>
        </DataTemplate>
    </Page.Resources>
</Page>

然后我可以使用templateKey="Test"从上面加载包含相同代码的页面。但主要问题是我想使用页面的第一个声明而不想使用<Page.Resources> <DataTemplate x:Key="Test">等等。我想直接从第一个声明加载网站(本文中的第一个代码)。如何直接从页面创建DataTemplate?或者是否有另一种方法将页面加载到ContentControl中?

1 个答案:

答案 0 :(得分:1)

没有理由在Page内使用ContentControlPageUserControl类的子类,它增加了对在Frame控件中使用以支持导航,后台堆栈/历史记录等的支持。您应该替换Page在XAML中使用UserControl并且代码落后,所以你最终会得到这样的结果:

<UserControl x:Class="ExampleApp.myControl2">
    <Grid x:Name="Content" Height="651" Width="941" Background="White">
        ...
        ...
    </Grid>
</UserControl>

如果您想将UserControl用作DataTemplate中的DataTemplate,可以将ContentControl本身放在<ContentControl xmlns:controls="using:ExampleApp"> <ContentControl.Resources> <DataTemplate x:Key="Test"> <controls:myControl2 /> </DataTemplate> </ContentControl.Resources> </ContentControl> 中:

{{1}}