Recently learned a nifty trick from Pete Blois about how to use a UserControl as a DataTemplate in Silverlight 2.  This is real handy, because it allows for a more WPF-like workflow, allowing a designer to create data templates in Blend. With this workflow, the designer can go ahead and build out the data template as a UserControl. He/she may need some help from the developer to wire up the data fields -- in fact, the recommendation would be that the developer maybe create a dummy project with all the fields for the designer and then the designer can party on. (I modeled this technique here for WPF and reskinning Flotzam.)

So, here's a real simple data template from a user control:

    d:DesignWidth="149" d:DesignHeight="36" Width="153" >

    <Grid x:Name="LayoutRoot" Background="#FFFF0000" >
        <TextBlock HorizontalAlignment="Left" VerticalAlignment="Top"
Text="{Binding}" TextWrapping="Wrap"/> </Grid> </UserControl>


Note the use of the {Binding} syntax, which will just default bind to the single property on my data class. You could of course name the property you are binding to in the more likely case that you had more properties in your class.

Then, the xaml file that actually uses this as a data template looks like this:

<UserControl x:Class="SilverlightApplication1.Page"
    Width="400" Height="300" 
    mc:Ignorable="d"> <UserControl.Resources> <SilverlightApplication1:DataSource x:Key="DataSourceDS" d:IsDataSource="True"/> </UserControl.Resources> <Grid x:Name="LayoutRoot" Background="White"> <ListBox Margin="8,8,165,8" ItemsSource="{Binding Items, Mode=OneWay,
Source={StaticResource DataSourceDS}}"
> <ListBox.ItemTemplate> <DataTemplate> <Grid Background='Blue' HorizontalAlignment='Stretch'> <SilverlightApplication1:DataView /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> </UserControl>

Note that in the attribute where I register the namespace for the datasource, I explicitly refer to the assembly.  This is a gotcha when doing this; normally you don't need to refer to the assembly if it is in the same class, but in this case you do.

And there you have it.  Download the code here if you'd like.