Typically, the template is associated with a particular piece of data, but it is often desirable to dynamically determine which template to use---can be based on either a property value or a global state. You can also use datatemplateselector when you really need a large replacement template.
Datatemplateselector provides a single method----selecttemplate that allows you to decide which template to use by executing any logic. You can find templates in the included elements, return some hard-coded templates, and even dynamically create templates for each entry.
First, create a class that inherits from Datatemplateselector and complete some of the logic that rotates in several templates. In this example, the XmlElement localname is found and the resource with that name is obtained from the container, as follows:
public class Localnametemplateselector:datatemplateselector
{public
override DataTemplate Selecttemplate ( Object Item,dependencyobject Container)
{
XmlElement data = Item as XmlElement;
if (data!= null)
{return
(FrameworkElement) container). FindResource (data. LocalName) as DataTemplate;
}
return null;
}
}
To initialize all the templates, three templates are built: The brown rectangle for the book, The Silver Circle for the CD, and the Blue circle for the DVD. Because the template selector will look for the local name of the XmlElement, you need to set the x:key for each template as follows:
<datatemplate x:key= "book" datatype= "{x:type sx:xmlelement}" > <stackpanel orientation= "Horizontal"
; <rectangle margin= "2" width= "height=" fill= "Brown"/> <textblock "Center" Tex t= "{Binding xpath= @Title}" ></TextBlock> </StackPanel> </DataTemplate> &
Lt;datatemplate x:key= "CD" datatype= "{x:type sx:xmlelement}" > <stackpanel orientation= "Horizontal" > <ellipse margin= "2" width= "height=" fill= "Silver"/> <textblock verticalalignm Ent= "Center" text= "{Binding xpath= @Title}" ></TextBlock> </StackPanel> </DATATEMPLATE&G
T
<datatemplate x:key= "DVD" datatype= "{x:type sx:xmlelement}" > <stackpanel orientation= "Horizontal" > <ellipse margin= "2" width= "height=" fill= "Blue"/> <textblock VerticalalIgnment= "Center" text= "{Binding xpath= @Title}" ></TextBlock> </StackPanel> </datatempla Te>
The rest is to associate the template selector with the listbox instead of setting the static template, which is as follows:
<listbox itemssource= "{Binding xpath=/media/*}" >
<ListBox.ItemTemplateSelector>
<l: Localnametemplateselector xmlns:l= "Clr-namespace:wpfprogressbardemo"/>
</listbox.itemtemplateselector >
</ListBox>