Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a DataTemplate in code?

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.

like image 705
Asim Sajjad Avatar asked Apr 10 '10 01:04

Asim Sajjad


People also ask

What is a DataTemplate?

A data template can contain elements that are each bound to a data property along with additional markup that describes layout, color and other appearance. DataTemplate is, basically, used to specify the appearance of data displayed by a control not the appearance of the control itself.

What is difference between ItemTemplate and DataTemplate?

You use the ItemTemplate to specify the visualization of the data objects. If your ItemsControl is bound to a collection object and you do not provide specific display instructions using a DataTemplate, the resulting UI of each item is a string representation of each object in the underlying collection.

What is difference between a ControlTemplate and a DataTemplate in WPF?

A ControlTemplate will generally only contain TemplateBinding expressions, binding back to the properties on the control itself, while a DataTemplate will contain standard Binding expressions, binding to the properties of its DataContext (the business/domain object or view model).


2 Answers

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.

like image 84
Josh Avatar answered Oct 09 '22 01:10

Josh


You can add a control like a TextBlock using a FrameworkElementFactory. Then you can add the TextBlockto 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;
like image 36
Byron Sommardahl Avatar answered Oct 09 '22 03:10

Byron Sommardahl