Same XamDataGrid different layouts for different types

In some cases you might be using Infragistic’s XamDataGrid with differing types. For example, maybe a couple of types have the same base class but each have differing properties that you need the grid to display or maybe you have heterogeneous data which you want to display in the same grid.

To do this we simply define different field layouts within the XamDataGrid and use the Key property to define which layout is used for which type.

Let’s look at a simple example which will display two totally different sets of columns for the data. Here’s the example classes

public class Train
{
   public string Route { get; set; }
   public int Carriages { get; set; }
}

public class Car
{
   public string Make { get; set; }
   public string Model { get; set; }
   public float EngineSize { get; set; }
}

as you can see, the classes do not share a common base class or implement a common interface. If we set up our XamDataGrid like this

<ig:XamDataGrid DataSource="{Binding}">
   <ig:XamDataGrid.FieldLayouts>
      <ig:FieldLayout Key="Train">
         <ig:Field Name="Route" />
         <ig:Field Name="Carriages" />
      </ig:FieldLayout>

      <ig:FieldLayout Key="Car">
         <ig:Field Name="Make" />
         <ig:Field Name="Model" />
         <ig:Field Name="EngineSize" />
      </ig:FieldLayout>
   </ig:XamDataGrid.FieldLayouts>
</ig:XamDataGrid>

we can then supply an IEnumerable (such as an ObservableCollection) with all the same type, i.e. Car or Train objects or a mixture of both.

The Key should have the name of the type which it’s field layout applies to. So for example, when Train objects are found in the DataSource, the Train FieldLayout is used hence the columns Route and Carriages will be displayed, likewise when Car objects are found the Car layout is used, thus Make, Model and EngineSize are displayed.

Note: The field layout is used for each row, i.e. the grid control doesn’t group all Trains together and/or all Cars, the rows are displayed in the order of the data and thus the field layouts are displayed each time the object type changes.