views:

568

answers:

4

How can I create dataTemplate in code (using C#) and then add 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.

A: 

Microsoft has a good article over at MSDN: "Data Templating Overview." I would start there.

Update: Eh, scratch that. I read over your requirement for "in code." I'll just leave the link here for whoever might stumble upon this post.

Cory Larson
A: 

You can add a control like a TextBlock using a FrameworkElementFactory. Then you can add the TextBlock to the VisualTree of the DataTemplate. Like so:

//Create binding object and set as mode=oneway
Binding binding = new Binding();
binding.Path = new PropertyPath("SomePropertyPathName");
binding.Mode = BindingMode.OneWay;

//get textblock object from factory and set binding
FrameworkElementFactory textElement = new FrameworkElementFactory(typeof(TextBlock));
textElement.SetBinding(TextBlock.TextProperty, binding);

//apply textblock to datatemplate
dataTemplate.VisualTree = textElement;
Byron Sommardahl
The OP says he's using Silverlight which as far as I know does not support FrameworkElementFactory.
Josh Einstein
So he is, My mistake.
Byron Sommardahl
+2  A: 

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

Josh Einstein
+1 This is correct. Personally I prefer to use LinqToXml objects to build the Xaml needed but ultimately a result string needs to be passed to XamlReader to create a DataTemplate programmatically.
AnthonyWJones