views:

88

answers:

2

In my application, I would like to have DataTemplates such that I can say:

  • These are the DataTemplates for use in a TreeView
  • These are the DataTemplates to use when showing the summary of an object
  • These are the DataTemplates to use when showing details

The only way I've seen to be able to do this is to create a DataTemplateSelector and manually return the DataTemplate (possibly by a naming convention) for the class I need. Is there any more elegant way of handling this situation?

+1  A: 

I'm not sure I completely understand what you're looking for, but you should just be able to define the DataTemplates in a ResourceDictionary at the scope that most makes sense for you (Application, Window, Element or external) with an x:Key of the data type they're meant for and they will automatically be selected by WPF's intrinsic data template selection engine.

For example:

<Window ...>
    <Window.Resources>
        <DataTemplate x:Key="{x:Type myns:MyDataType}">
           <!-- your template definition here -->
        </DataTemplate>
    </Window.Resources>
</Window>

Now wherever an instance of MyDataType is encountered within that Window WPF will automatically select that template to display its data.

Drew Marsh
A: 

you can set DataType property of DataTemplate. At runtime template will automatically assigned to object of its Type.

viky