Search code examples
c#wpfsilverlightxamldatatemplate

Data Template are only necessary in ItemsControl controls?


Let me explain you my situation.

I have a base class called Shape, and several concrete classes like Triangle, Square, etc.

I have several data templates.

I'm building just one object. So I wouldn't use an ItemControl control, I would like to use a normal panel like the grid, and show the respective data template (in DataContext has the concrete item)..

The only way to do this is using an ItemsControl? Or there's another way.. because I'm just using one item and not a collection and display the correct template.


Solution

  • DataTemplates are used in much more than just ItemsControls

    They are used to tell WPF how to draw any object in the Visual Tree. For example, if you stick a User class object in the VisualTree, a DataTemplate can be used to tell WPF how to draw that User object

    They are most frequently used in controls with an ItemsSource or Content properties, because those are the most common way of inserting data objects into the VisualTree.

    In your specific case where you only want to insert one data item into the VisualTree, I would suggest a ContentControl

    <ContentControl Content="{Binding MyDataObject}" />
    

    To tell WPF how to draw MyDataObject you can either use the ContentTemplate property and set it to a DataTemplate

    <ContentControl Content="{Binding MyDataObject}" 
                    ContentTemplate="{StaticResource MyDataTemplate}" />
    

    or define an implicit DataTemplate that tells WPF to draw any object of a specific type using a specific template.

    <DataTemplate DataType="{x:Type local:MyDataObject}">
        <!-- Tell WPF how to draw MyDataObject here -->
    </DataTemplate>