How do I add multiple controls to a DataGridTemplateColumn of a datagrid using wpf?

IanM picture IanM · Jan 20, 2011 · Viewed 12.6k times · Source

I have several instances where I would like to have several controls in a single column in a datagrid.

For example, I have a dataset that contains images with matching description, image source, timestamp, geotag, etc. I would like to display this information with a thumbnail image in one column and the majority of data in either a textbox or a label. Other datasets I have require textbox / checkbox, or textbox / combobox.

When I attempt to add a second control I receive an error reporting that The property "VisualTree" is set more than once.

<DataGridTemplateColumn Header="Data" Width="100">
    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Label Name="Description" Content="{Binding Desc}"></Label>
            <Label Name="Camera" Content="{Binding Camera}"></Label>
        </DataTemplate>      
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

Answer

Austin Lamb picture Austin Lamb · Jan 20, 2011

The DataTemplate should have only one element, I believe - so you should use a Panel to contain the elements, say something like this:

<DataGridTemplateColumn Header="Data" Width="100">
    <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
             <StackPanel Orientation="Horizontal">
                 <Label Name="Description" Content="{Binding Desc}"></Label>
                 <Label Name="Camera" Content="{Binding Camera}"></Label>
             </StackPanel>
         </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> 

You could of course use WrapPanel, Grid, or anything else you like - StackPanel just appears to be what you're going for.