3

How is a DataTemplate applied to a Grid?

I have a DataTemplate named DataGrid_Template in my Resources.xaml file that I would like to apply to a Grid in View.xaml.


Resources.xaml

<ResourceDictionary ... >
    <DataTemplate x:Key="DataGrid_Template">
        <Grid>
            <Grid.RowDefinitions ... />
            <DockPanel ... />
            <DataGrid ... />
        </Grid>
    </DataTemplate>
</ResourceDictionary>


View.xaml

<UserControl ... >
    <Grid /> <!-- want to apply DataGrid_Template to this -->
</UserControl>


I tried using the Grid property TemplatedParent, but that seems to be a read-only property.

mauryat
  • 1,610
  • 5
  • 29
  • 53
  • Are you trying to use the Grid as an `ItemsControl`, or as something more complex? – Kyeotic Jul 10 '12 at 19:47
  • see those links: http://stackoverflow.com/questions/3251081/is-there-a-datatemplate-for-grid-panel-elements-in-wpf , http://stackoverflow.com/questions/3223174/changing-wpf-stackpanel-template -> you can't do it directly – Clueless Jul 10 '12 at 19:50
  • @Tyrsius I'm not using the `Grid` as an `ItemsControl`. See the updated code-snippet for `Resources.xaml`. I'm trying to have a `DockPanel` and a `DataGrid`. – mauryat Jul 10 '12 at 20:11
  • @Clueless @Tyrsius Sorry, I think I got everyone confused with a typo in my code-snippet. I meant `DataTemplate`, but incorrectly typed in `ControlTemplate`. – mauryat Jul 10 '12 at 21:19

1 Answers1

12

You cannot apply DataTemplates to panels (e.g. Grid).

If you just want that template placed somwhere then you can use a ContentControl and set it as the ContentTemplate via StaticResource.

(ContentControl.Content needs to be set to something, otherwise the ContentTemplate is not applied, if there is no real "content" setting the Template instead should work as well.)

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • That worked perfectly well! Sorry I think I confused everyone with a typo in my code-snipped. I meant `DataTemplate`, but incorrectly typed in `ControlTemplate`. – mauryat Jul 10 '12 at 21:18
  • 1
    @user640378: A control template would probably work as well (as you do not appear to have any data that is used in the `Content`), you'd just assign it as the `ContentControl.Template`. – H.B. Jul 10 '12 at 21:23
  • 1
    In case anyone is wondering, here's an example of the XAML to use the DataTemplate, where GridSettingsTemplate is the name of your DataTemplate containing the defition for the grid. Set HorizontalAlignment and VerticalAlignment to Stretch or your grid will look different than before you migrated it into the DataTemplate: – John Mar 18 '14 at 21:45
  • 1
    To add to this answer, I also had to set Content={Binding} on the ContentControl to get this to work (got the idea from here http://stackoverflow.com/a/15389304/2868438) – Quails4Eva May 12 '15 at 11:38