Pages

Saturday, 3 March 2012

DataType instead of DataTemplateSelector

Nearly three years ago I posted about the use of the DataTemplateSelector.
It transpires that because I was using different types of objects in my ItemsSource I could have used the DataType attribute of the DataTemplate.
Define the DataTemplates in the usual way but add the DataType attribute.
      <DataTemplate DataType="{x:Type dts:BookingLineItem}">
      <DataTemplate DataType="{x:Type dts:CCardPaymentLineItem}">
      <DataTemplate DataType="{x:Type dts:CashPaymentLineItem}">
      <DataTemplate DataType="{x:Type dts:LineItem}">
There is no need to define the DataTemplateSelector in the resources, no C# class to write and the ListBox becomes simpler:
      <ListBox Name="theSecondTillRoll"
               Height="150"
               Width="330"
               ItemsSource="{Binding SaleItems}" />
The DataTemplateSelector project is on GoogleCode and demonstrates both techniques.

No comments: