带有 TextBlock 的 WPF DataGridCell 模板 - 绑定?
我用 TextBlock
替换 DataGridCell
的 Template
中的 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>
由于您删除了 ContentPresenter
,DataGridCell
无法显示其 Content
.虽然它仍然存在.DataGridCell.Content
是一个包含原始 Text
的 TextBlock
,Template
中的 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>