Michael Hedgpeth
Michael Hedgpeth

Reputation: 7862

How to have classes of DataTemplates?

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

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?

Upvotes: 2

Views: 148

Answers (2)

viky
viky

Reputation: 17689

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

Upvotes: 0

Drew Marsh
Drew Marsh

Reputation: 33379

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.

Upvotes: 2

Related Questions