How to define a DataTemplate in code?

Asim Sajjad picture Asim Sajjad · Apr 10, 2010 · Viewed 15.4k times · Source

How can I create a DataTemplate in code (using C#) and then add a control to that DataTemplate?

<data:DataGrid.RowDetailsTemplate>
    <DataTemplate>
        <Border>
            <Border Margin="10" Padding="10" BorderBrush="SteelBlue" 
                 BorderThickness="3" CornerRadius="5">
                <TextBlock Text="{Binding Description}" TextWrapping="Wrap" 
                     FontSize="10">
                </TextBlock>
            </Border>
        </Border>
    </DataTemplate>
</data:DataGrid.RowDetailsTemplate>

I am using Sivlerlight.

Answer

Josh picture Josh · Apr 10, 2010

As far as I know, the only way to create a DataTemplate in Silverlight is to use XamlReader. Basically you would just pass it the XAML as a string and it will give you back a DataTemplate. Byron's solution would apply to WPF but Silverlight (to the best of my knowledge) does not support FrameworkElementFactory.

Scott Morrison: Defining Silverlight DataGrid Columns at Runtime

Take note of option #2 for DataGridTemplateColumn.