The WPF DataTemplate has a DataType property. What this enables is a matching of Clr object Type to a specific DataTemplate to be applied when that object type is used as content for a ContentControl or ItemsControl. This is very handy especially in MVVM scenarios.

In DotNetBar for Silverlight we have implemented a feature which is meant to simulate the typed data template found in WPF. The basic implementation is simply an attached property defined in the static class TypedDataTemplate. The name of the attached property is DataType and it can be applied directly to any regular Silverlight DataTemplate which you define in the Resources collection of a control in the visual tree. Class TypedDataTemplate also exposes a public method named FindDataTemplateForType. FindDataTemplateForType takes a FrameworkElement and Type as parameters. It searches resources collections of the elements of the visual tree, beginning with the FrameworkElement supplied as parameter value. It looks for a DataTemplate that has a value for TypedDataTemplate.DataType matching the Type parameter value. It returns the first match it finds, or null if no match is found.

The DataType property value can be either a fully qualified Type name or it’s short name, in which case all available assemblies are searched. (Using fully qualified name is both more performant and more robust.) Here is an example of a DataTemplate with the DataType attached property:

(ctrls = namespace DevComponents.Silverlight.Controls)

<DataTemplate x:Key="MenuViewModelDataTemplate" ctrls:TypedDataTemplate.DataType="MenuViewModel">
    <ctrls:Menu ItemsSource="{Binding ItemsSource}" ItemTemplate="{Binding ItemTemplate}" 
                Command="{Binding Command}" CommandParameter="{Binding CommandParameter}" />
</DataTemplate>

The typed data template pattern is used internally by the ItemsHostControl and all controls which inherit from it.

Additionally, class ContentHostControl which inherits from Silverlight’s ContentControl will search for a typed data template to use as the value for property ContentTemplate when the control’s Content property changes.

Related posts:

  1. ItemsHostControl Control
  2. Customizing Month View Days in Silverlight Schedule
  3. Dynamic Resources
  4. SuperToolTip Control
  5. Navigation Pane Quick Start Guide (Silverlight)