Implicit DataTemplates for Control in Silverlight 5 Beta

By | April 14, 2011

As this is a new features if Silverlight 5 beta, you need  below prerequisite To try the features

  1. You first need to download Visual Studio 2010 (SP 1) if you didn’t have done that already. 
  2. After you install Visual studio update you need Silverlight tools for Visual Studio

  3. Optionally you can also try Silverlight help tools to get started.

If you are a WPF developer reading this, you might be thinking that it should be already present before, but it isnt. For Silverlight developers there is a new adjustments made to ensure that DataTemplates are loaded based on Type of Data.

Say you own a ListBox with custom DataTemplate as shown below :

<Grid>
    <Grid.Resources>
        <DataTemplate DataType="local:Abhishek">
            <Border Background="Red">
                <TextBlock Text="Abhishek's Template Selected" />
            </Border>
        </DataTemplate>
        <DataTemplate DataType="local:Abhijit">
            <Border Background="Green">
                <TextBlock Text="Abhijit's Template Selected" />
            </Border>
        </DataTemplate>
    </Grid.Resources>
    <ListBox ItemsSource="{Binding ListofPeople}" Grid.Row="0"/>
</Grid> 

Here you can see a new property called DataType which has been already present with WPF earlier but recently added with silverlight, will let you specify the type of the object for which the DataTemplate is associated with.
Now if we create the ListofPeople with both objects of Abhishek and Abhijit, it will automatically select the type based on the individual DataType.

public class Model
{
    private List<People> listofPeople;
    public List<People> ListofPeople
    {
        get
        {
            this.listofPeople = this.listofPeople ?? this.LoadListofPeople();
            return this.listofPeople;
        }
    }

    private List<People> LoadListofPeople()
    {
        List<People> peop = new List<People>();
        peop.Add(new Abhishek());
        peop.Add(new Abhijit());
        peop.Add(new Abhishek());
        return peop;
    }
}

If you force the Model into DataContext, it will choose DataTemplate according to the type passed.