views:

72

answers:

1

I have DataTemplate, written in XAML

<DataTemplate x:Key="AnalogTemplate" x:Name="AnalogTemplate" >
                        <TextBox  Text="{Binding parameter}" Background="Black"/>
                    </DataTemplate>

And I have some DataGrid

How to apply DataTemplate "AnalogTemplate" to the one specified column in DataGrid programmaticaly in C# ?

+1  A: 

You can use the DataGridTemplateColumn. I assume you want to set a default template in xaml and overwrite it later in code. Here I set it to MyDefaultTemplate, which should be defined in the control's resources together with your AnalogTemplate:

    <DataGrid AutoGenerateColumns="False" Height="200" Name="dataGrid1" Width="200">
        <DataGrid.Columns>
            <DataGridTemplateColumn x:Name="myColumn" CellTemplate="{StaticResource MyDefaultTemplate}"/>                
        </DataGrid.Columns>
    </DataGrid>

Then you can easily change it in code:

myColunm.CellTemplate = (DataTemplate) FindResource("AnalogTemplate");

Before doing anything in code you should ask yourself if you can do it in pure xaml instead, Often you can. Also check out CellTemplateSelector and CellEditingTemplateSelector.

Note that a DataGrid uses two templates. One for displaying non-editable content (CellTemplate) and one for editable content (CellEditingTemplate). See DataGridTemplateColumn at MSDN.

Holstebroe
thank you very much
Timur