Implicit DataTemplates for Control in Silverlight 5 Beta

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.

Abhishek Sur

Abhishek Sur is a Microsoft MVP since year 2011. He is an architect in the .NET platform. He has profound theoretical insight and years of hands on experience in different .NET products and languages. He leads the Microsoft User Group in Kolkata named KolkataGeeks, and regularly organizes events and seminars in various places for spreading .NET awareness. He is associated with the Microsoft Insider list on WPF and C#, and is in constant touch with product group teams. He blogs at http://www.abhisheksur.com His Book : Visual Studio 2012 and .NET 4.5 Expert Development Cookbook. Follow Abhishek at Twitter : @abhi2434