4

i replace the ContentPresenter in the DataGridCell's Template with a TextBlock an now i search for the correct Binding to the content.

The normal way is Text="{TemplateBinding Content} for the TextBlock - it doesn't work. Also Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content, Mode=TwoWay}" doesn't work correct.

Any other ideas?

Julien Lebosquain
  • 40,639
  • 8
  • 105
  • 117
frank_funk
  • 183
  • 2
  • 3
  • 11

2 Answers2

16

Suppose you have changed the DataGridCell Template to the following

<ControlTemplate TargetType="{x:Type DataGridCell}">
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
        <TextBlock Text="{Binding}"/>
        <!--<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> -->
    </Border>
</ControlTemplate>

Since you removed the ContentPresenter, the DataGridCell has no way of displaying its Content. It's still there though. The DataGridCell.Content is a TextBlock containing your original Text and the TextBlock in the Template is another.

So you'll get the correct Text by binding it to the Content.Text property of the TemplatedParent

<TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent},
                          Path=Content.Text}"/>

So, to sum it up. This works

<ControlTemplate TargetType="{x:Type DataGridCell}">
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
        <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                                  Path=Content.Text}"/>
    </Border>
</ControlTemplate>
Fredrik Hedblad
  • 83,499
  • 23
  • 264
  • 266
1

The data context of the data grid cell should be the data itself. So the binding should simply be:

<TextBlock Text="{Binding}"/>
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 5
    The `DataGridCell` has the same `DataContext` as the `DataGridRow` so you'll need a path. And if you want this to be generic, you can't set a path. I don't think this works – Fredrik Hedblad Aug 23 '11 at 13:03