正如我所看到的,很多人都遇到了这个问题,但我不明白为什么我的案例不起作用,它开始让我发疯。
背景:我有一个DataGrid
将根据每个单元格的值着色。因此,我有一个动态样式来解析每个单元格使用的实际模板。背景现在可以相应地工作。
新问题:当我有深色背景时,我希望字体颜色为白色,字体粗细为粗体,以便文本可以正确阅读。而且...我无法正确设置它的样式。
我读过一些 Stackoverflow 的帖子:
这适合我的问题,但没有为我提供任何可行的解决方案 https://stackoverflow.com/questions/4739530/how-to-change-textblock-default-properties-for-a-contentpresenter-in-a-template
这也很清楚和详细,但是......呃 https://stackoverflow.com/questions/3063264/contentpresenter-within-controltemplate-cannot-change-attached-dependency-propert
这几乎与我相同的问题,但是......解决方案不起作用 https://stackoverflow.com/questions/3970285/wpf-4-contentpresenter-textwrapping-style-is-not-applied-to-implicitedly-generate
这是我到目前为止所尝试的:
<!-- Green template-->
<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
<Grid Background="Green">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ContentPresenter.Resources>
<Style BasedOn="{StaticResource BoldCellStyle}" TargetType="{x:Type TextBlock}" />
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
</ControlTemplate>
不起作用。背景是绿色的,但文本保持黑色且不是粗体。
顺便说一句,BoldCellStyle 非常简单:
<Style x:Key="BoldCellStyle" TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="White" />
</Style>
好的。第二次尝试(这确实是一个愚蠢的尝试,但好吧......)
<!-- Green template -->
<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
<Grid Background="Green">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ContentPresenter.Resources>
<Style x:Key="BoldCellStyle" TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="White" />
</Style>
</ContentPresenter.Resources>
</ContentPresenter>
</Grid>
</ControlTemplate>
也不行。
然后,我尝试玩ContentPresenter
的属性:
<!-- Green template -->
<ControlTemplate x:Key="Green" TargetType="{x:Type tk:DataGridCell}">
<Grid Background="Green">
<ContentPresenter TextElement.FontWeight="Bold" TextElement.Foreground="White" TextBlock.Foreground="White"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
而且...正如您所料,这甚至不起作用。
出于好奇,我使用 Snoop 浏览了界面的所有组件。
在前两种情况下,Snoop 实际上向我展示了每个单元格都是一个Grid
with a ContentPresenter
含有一个TextBlock
和实际的Style
但是...TextBlock
的属性不适用并且FontWeight
还是正常的。
最后一个案例,更令人震惊的是,我可以看到窥探向我表明我们实际上有一个ContentPresenter
具有正确的属性(即TextElement.FontWeight="Bold"
),但是自动生成的TextBlock
下面 - 仍然 - 没有样式。
我不明白我在这里缺少什么。正如你所看到的,我尝试了几乎所有我能在这里做的事情,并且TextBlock
s 保持未格式化。
这里有什么想法吗?再次感谢!