我有个数据。有些单元格的颜色取决于它们的值。这个很好用。
问题是,当我将文本居中时,单元格就会失去颜色,字体是彩色的,但我希望单元格也被填充。
下面是我的代码,它填充单元格并更改字体颜色,唯一缺少的是文本没有居中。
<Setter Property="HorizontalAlignment" Value="Center"/>当我在上面添加行时,就像我说的那样,虽然字体已经不着色了,为什么呢?
<DataGridTextColumn Header="BTBL" IsReadOnly="True" MinWidth="75" Binding="{Binding BTBL.DisplayString}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="FontWeight" Value="Bold"/>
<Style.Triggers>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="GREEN">
<Setter Property="Background" Value="LightGreen"/>
<Setter Property="Foreground" Value="DarkGreen"/>
</DataTrigger>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="YELLOW">
<Setter Property="Background" Value="LightYellow"/>
<Setter Property="Foreground" Value="DarkKhaki"/>
</DataTrigger>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="RED">
<Setter Property="Background" Value="LightCoral"/>
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>发布于 2015-12-17 16:41:30
编辑: As @ChrisW。评论部分提到,TextAlignment=Center才是真正的答案,您不需要围绕Textblock设置包装器。因为这是目前唯一的答案,我在这里留下一个编辑,而不是完全撤回它。下面的代码可以用于处理没有TextAlignment或HorizontalContentAlignment选项的其他情况。
实际上,这段代码的工作原理是应该的。当您说HorizontalAlignment=Center时,TextBlock缩小到它的内容长度,然后在容器中居中。为了实现您想要的结果,您需要在居中的文本块周围添加一个包装器控件,然后处理完整的单元格宽度填充。
<DataGridTemplateColumn Header="BTBL" IsReadOnly="True" MinWidth="75">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border BorderThickness="0">
<TextBlock Text="{Binding BTBL.DisplayString}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="HorizontalAlignment" Value="Center" />
<Style.Triggers>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="GREEN">
<Setter Property="Foreground" Value="DarkGreen"/>
</DataTrigger>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="YELLOW">
<Setter Property="Foreground" Value="DarkKhaki"/>
</DataTrigger>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="RED">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<Border.Style>
<Style TargetType="{x:Type Border}">
<Style.Triggers>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="GREEN">
<Setter Property="Background" Value="LightGreen"/>
</DataTrigger>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="YELLOW">
<Setter Property="Background" Value="LightYellow"/>
</DataTrigger>
<DataTrigger Binding="{Binding BTBL.ColourCode}" Value="RED">
<Setter Property="Background" Value="LightCoral"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>https://stackoverflow.com/questions/34337427
复制相似问题