如何在UWP Windows 10中重用XAML中的网格

时间:2015-10-13 12:23:21

标签: xaml windows-10 uwp

我目前有一个带有3个网格的Pivot和一个具有相同网格的ScrollViewer。正如任何软件工程师所做的那样,我想只需要一次代码,而不是两次。所以我的问题是:我该怎么做?

1 个答案:

答案 0 :(得分:4)

得到了解决方案:我将三个网格放在三个单独的DataTemplates中,并从Pivot内部和ScrollViewer中引用这些模板:

<Page.Resources>
   ...
   <DataTemplate x:Key="JustANormalGridNr1">
      <Grid />
   </DataTemplate>
   <DataTemplate x:Key="JustANormalGridNr2">
      <Grid />
   </DataTemplate>
   <DataTemplate x:Key="JustANormalGridNr3">
      <Grid />
   </DataTemplate>
</Page.Resources>

<Grid x:Name="MasterGrid">
   <Pivot>
      <Pivot.Items>
         <PivotItem>
            ...
            <Grid>
               <ContentControl ContentTemplate="{StaticResource JustANormalGridNr1}" /><!--instead of the grid, a reference to it -->
            </Grid>
         </PivotItem>
         <PivotItem>
            ...
            <Grid>
               <ContentControl ContentTemplate="{StaticResource JustANormalGridNr2}" /><!--instead of the grid, a reference to it -->
            </Grid>
         </PivotItem>
         <PivotItem>
            ...
            <Grid>
               <ContentControl ContentTemplate="{StaticResource JustANormalGridNr3}" /><!--instead of the grid, a reference to it -->
            </Grid>
         </PivotItem>
      </Pivot.Items>
   </Pivot>

   <ScrollViewer>
      <Grid>
         <Grid>
            ...
            <Grid Grid.Column="0">
               ...
               <ContentControl Grid.Row="1" ContentTemplate="{StaticResource JustANormalGridNr1}" /><!-- Instead of the grid, a reference to it -->
            </Grid>
            <Grid Grid.Column="1">
               ...
               <ContentControl Grid.Row="1" ContentTemplate="{StaticResource JustANormalGridNr2}" /><!-- Instead of the grid, a reference to it -->
            </Grid>
            <Grid Grid.Column="2">
               ...
               <ContentControl Grid.Row="1" ContentTemplate="{StaticResource JustANormalGridNr3}" /><!-- Instead of the grid, a reference to it -->
            </Grid>
         </Grid>
      </Grid>
   </ScrollViewer>
</Grid>