Windows phone 8.1 Windows Phone 8.1-创建模板并在许多地方使用它?

Windows phone 8.1 Windows Phone 8.1-创建模板并在许多地方使用它?,windows-phone-8.1,winrt-xaml,windows-8.1-universal,Windows Phone 8.1,Winrt Xaml,Windows 8.1 Universal,我有一个场景,我需要创建模板并在许多地方使用它 例如: <Grid VerticalAlignment="Top" Background="White"> <TextBlock Foreground="Black" FontSize="24" FontWeight="SemiBold" Margin="12 12 12 6"/> <Border Background="DarkGray" HorizontalAlignment="Left" Height="2"

我有一个场景,我需要创建模板并在许多地方使用它

例如:

<Grid VerticalAlignment="Top" Background="White">
<TextBlock  Foreground="Black" FontSize="24" FontWeight="SemiBold" Margin="12 12 12 6"/>
<Border Background="DarkGray" HorizontalAlignment="Left" Height="2" Width="170" Margin="12 0 0 12"/>
<Border Background="DarkGray" HorizontalAlignment="Right" Height="2" Width="170" Margin="12 0 0 12"/>
我面临的问题是,第一次它工作正常,当我返回并再次导航时,它抛出异常“该元素已经是另一个元素的子元素”

请告诉我这是一个正确的方法还是有其他方法

PS:我想创建几百个这样的模板,所以我不能使用用户控制


提前谢谢。

有一个更简单的方法。将“模板”定义为
ControlTeplate

<ControlTemplate  x:Key="specificationTemplate1">
    <Grid VerticalAlignment="Top" Background="White">
    <TextBlock  Foreground="Black" FontSize="24" FontWeight="SemiBold" Margin="12 12 12 6"/>
    <Border Background="DarkGray" HorizontalAlignment="Left" Height="2" Width="170" Margin="12 0 0 12"/>
    <Border Background="DarkGray" HorizontalAlignment="Right" Height="2" Width="170" Margin="12 0 0 12"/>
    </Grid>
</ControlTemplate>
还是密码

var c = new ContentControl
{
    Template = (ControlTemplate)App.Current.Resources["specificationTemplate1"]
}

再次导航时,是否检查(MainGird.Children.Contains(grdsspecificationTemplate))?这可能会解决问题。如果已经添加了,你不必再添加ir。这不会解决我的问题。ControlTemplate和DataTemplate只能与常规项一起使用。如何以编程方式获取模板(即网格)内的内容?可以在ControlTemplate内使用绑定,并为创建的ContentControl设置DataContext。但是读了这篇文章,我认为创建一个UserControl对你来说会更好。这就是我最初提到的,我不能使用UserControl,因为需要100多个模板,在这些模板中我最终会得到100页的UserControl。在这种情况下,无论你使用什么,性能都会很差。考虑画画做画布。
<ControlTemplate  x:Key="specificationTemplate1">
    <Grid VerticalAlignment="Top" Background="White">
    <TextBlock  Foreground="Black" FontSize="24" FontWeight="SemiBold" Margin="12 12 12 6"/>
    <Border Background="DarkGray" HorizontalAlignment="Left" Height="2" Width="170" Margin="12 0 0 12"/>
    <Border Background="DarkGray" HorizontalAlignment="Right" Height="2" Width="170" Margin="12 0 0 12"/>
    </Grid>
</ControlTemplate>
<ContentControl Template="{StaticResource specificationTemplate1" />
var c = new ContentControl
{
    Template = (ControlTemplate)App.Current.Resources["specificationTemplate1"]
}