Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different item template for each item in a WPF List?

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?

like image 557
Phil Wright Avatar asked Sep 30 '08 11:09

Phil Wright


People also ask

What is difference between a ControlTemplate and a DataTemplate in WPF?

A ControlTemplate will generally only contain TemplateBinding expressions, binding back to the properties on the control itself, while a DataTemplate will contain standard Binding expressions, binding to the properties of its DataContext (the business/domain object or view model).

What is ItemTemplate WPF?

You use the ItemTemplate to specify the visualization of the data objects. If your ItemsControl is bound to a collection object and you do not provide specific display instructions using a DataTemplate, the resulting UI of each item is a string representation of each object in the underlying collection.

What is DataTemplate WPF?

DataTemplate is about the presentation of data and is one of the many features provided by the WPF styling and templating model. For an introduction of the WPF styling and templating model, such as how to use a Style to set properties on controls, see the Styling and Templating topic.


2 Answers

the ItemTemplateSelector will work but I think it is easier to create multiple DataTemplates 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

like image 178
rudigrobler Avatar answered Oct 20 '22 09:10

rudigrobler


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/

like image 32
Matt Hamilton Avatar answered Oct 20 '22 11:10

Matt Hamilton