15

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?

ari k
  • 179
  • 1
  • 8

1 Answers1

3

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>
ChrisO
  • 5,068
  • 1
  • 34
  • 47
  • 1
    The problem is the lack of Binding possibility when I define a templatecolumn. There doesn't seem to be a way for me to say that first column should give the field Title to the template to show. – ari k Jul 05 '13 at 06:37
  • The datatemplate of the template column is already supplied with the row's data context. – Gman May 29 '15 at 18:05
  • But the row data context needs to be set right? if DataGridTemplateColumn doesnt support binding how can we set the context for the row – keerthee Jan 08 '20 at 11:42
  • 1
    I dont understand the upvotes. it does not solve the problem in the question – Welcor Aug 19 '20 at 16:11