I have many items inside a list control. I want each item to have a different item template depending on the type of the item. So the first item in the list is a ObjectA type and so I want it to be rendered with ItemTemplateA. Second item is a ObjectB type and so I want it to have ItemTemplateB for rendering. At the moment I can only use the ItemTemplate setting to define one template for them all. Any way to achieve this?
2 Answers
the ItemTemplateSelector
will work but I think it is easier to create multiple DataTemplate
s in your resource section and then just giving each one a DataType
. This will automatically then use this DataTemplate
if the items generator detects the matching data type?
<DataTemplate DataType={x:Type local:ObjectA}>
...
</DataTemplate>
Also make sure that you have no x:Key
set for the DataTemplate
.
Read more about this approach here

- 53,997
- 54
- 186
- 290

- 17,045
- 12
- 60
- 74
-
4I forgot to put in the {x:Type... stuff, please try again! – rudigrobler Sep 30 '08 at 13:28
-
1Also make sure that you have no x:Key set! – rudigrobler Sep 30 '08 at 13:32
-
2it seems the link is dead.. Do you have any similar source to refer to? – default May 13 '13 at 08:02
-
The quotes around {x:Type local:Object} are missing. And here is a [link](https://www.codeproject.com/Articles/31837/Creating-an-Internationalized-Wizard-in-WPF) to a similar solution with ItemsControl and DataType binding in WPF. – user8276908 May 06 '20 at 20:36
Have a look at the ItemTemplateSelector property of your list control. You can point it to a custom TemplateSelector and decide which template to use in code.
Here's a blog post describing TemplateSelectors:
http://blogs.interknowlogy.com/johnbowen/archive/2007/06/21/20463.aspx
Edit: Here's a better post:
http://blog.paranoidferret.com/index.php/2008/07/16/wpf-tutorial-how-to-use-a-datatemplateselector/

- 200,371
- 61
- 386
- 320