Search code examples
wpfdatatemplate

What is the format of the DataType property for a DataTemplate or HierarchicalDataTemplate in WPF?


I am trying to understand what the format is for the DataType parameter for a DataTemplate or a HierarchicalDataTemplate. There are lots of examples scattered throughout the internet that I can copy and get working, but I don't understand what my options are.

For example:

<DataTemplate DataType="{x:Type model:DepartmentSelectionViewModel}">

I would like to understand what x:Type means. And what model:DepartmentSelectionViewModel means.

Or:

<HierarchicalDataTemplate DataType="{x:Type r:NetworkViewModel}" ItemsSource="{Binding Children}">

Again, it has x:Type. But this time r:NetworkViewModel.

Other examples will have sys: or local:. What do all these settings mean? How can I discover what other settings exist? (Is settings even the right word to describe them?)


Solution

  • model and r refer to XAML namespace mappings.

    These are ofter found in the root tag or the XAML file and define the CLR namespaces in which the types (classes) DepartmentSelectionViewModel and NetworkViewModel are defined respectively:

    <Window ... xmlns:model="clr-namespace:Project1" ... />
    

    namespace Project1
    {
        public class DepartmentSelectionViewModel { ... } 
    }
    

    You can define as many namespace mappings as you want.

    x:Type refers to a type for which the implicit DataTemplate will be applied, i.e. the DataTemplate with the DataType property set to {x:Type model:DepartmentSelectionViewModel} will be applied to all DepartmentSelectionViewModel objects in the Items collection of the TreeView when the view is rendered.