itemtemplate selection by type in xaml only

some days ago i found my self in need to change the itemtemplate in a listbox according to their type. and if with less code as possible. i had done this in a treeview but i couldnt find the code again. so i needed to figure it out again and with some help from a collegue we ended with this:


<!-- more xaml here -->

<ItemsControl ItemsSource="{Binding Items}">
  <ItemsControl.Resources>
    <DataTemplate DataType="{x:Type MyNameSpace:MyType1}">
      <RadioButton />
    </DataTemplate>
    <DataTemplate DataType="{x:Type MyNameSpace:MyType2}">
      <ComboBox  />
    </DataTemplate>
    <DataTemplate DataType="{x:Type MyNameSpace:MyType3}">
      <TextBox />
    </DataTemplate>
  </ItemsControl.Resources>
</ItemsControl>

<!-- more xaml here -->

remark: you arent allowed to give a key to that resources. i suppose the type is kind of key here.

Leave a Comment