WPF DataGridCell Template with TextBlock - Binding?

余生长醉 提交于 2019-12-05 12:22:08

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>

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

<TextBlock Text="{Binding}"/>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!