带有 TextBlock 的 WPF DataGridCell 模板 - 绑定? [英] WPF DataGridCell Template with TextBlock - Binding?

查看:49
本文介绍了带有 TextBlock 的 WPF DataGridCell 模板 - 绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 TextBlock 替换 DataGridCellTemplate 中的 ContentPresenter 现在我搜索正确绑定到内容.

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

对于 TextBlock,通常的方法是 Text="{TemplateBinding Content} - 它不起作用.另外 Text="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content, Mode=TwoWay}" 无法正常工作.

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.

还有其他想法吗?

推荐答案

假设你已经将 DataGridCell Template 更改为以下内容

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>

由于您删除了 ContentPresenterDataGridCell 无法显示其 Content.虽然它仍然存在.DataGridCell.Content是一个包含原始 TextTextBlockTemplate 中的 TextBlock 是另一个.

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.

因此,通过将其绑定到 TemplatedParent

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}"/>

总结一下.这有效

<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>

这篇关于带有 TextBlock 的 WPF DataGridCell 模板 - 绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆