C# – Binding DataGridTemplateColumn

cdatagriddatagridtemplatecolumndatatemplatewpf

Seems I've hit a wall trying to use DataTemplates on my DataGrid. What I'm trying to do is to use one template to show two rows of text for each cell. But it doesn't seem to be possible to Bind the column in any way.

Following code hopefully shows what I wish to do. Note the Binding for each column: there is no such thing for a template column, and as such, this xaml couldn't possibly work.

<Window.Resources>
    <DataTemplate x:Key="DoubleField">
        <StackPanel>
            <TextBlock Text="{Binding Value1}"/>
            <TextBlock Text="{Binding Value2}"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<DataGrid>
    <DataGrid.Columns>
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Title}"/> // <- Binding does not exist for templatecolumn, I only wish it did
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Price}"/> // <- Binding does not exist for templatecolumn, I only wish it did
        <DataGridTemplateColumn CellTemplate="{StaticResource DoubleField}" Binding="{Binding Stuff}"/> // <- Binding does not exist for templatecolumn, I only wish it did
    </DataGrid.Columns>
</DataGrid>

class MyListItem {
    class DoubleItem {
        string Value1 { get; set; }
        string Value2 { get; set; }
    }    
    DoubleItem Title { get; set; }
    DoubleItem Price { get; set; }
    DoubleItem Stuff { get; set; }
}

Am I doomed to copy the whole DataTemplate to every column just to have a different binding on each copy? Surely there a nice way to go around this? Or am I just missing something blindingly obvious again?

Best Answer

I'm not completely sure what you're trying to do but if you need to get the DataContext of the whole row, you can use a RelativeSource binding to walk up the visual tree. Like so:

<DataTemplate x:Key="DoubleField">
    <StackPanel>
        <TextBlock Text="{Binding DataContext.Value1, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
        <TextBlock Text="{Binding DataContext.Value2, RelativeSource={RelativeSource AncestorType=DataGridRow}}"/>
    </StackPanel>
</DataTemplate>
Related Topic