I'm working with a WPF DataGrid. I'm trying to get the contents of my DataGridTextColumns to center the displayed text vertically.
Currently, my cell values look like this: https://i.sstatic.net/vqjKO.jpg. As you can see, they are vertically aligned towards the top of the cells.
I tried adding a template to the style of my DataGridCells, this works, and it centers the text like so: https://i.sstatic.net/fq4hi.jpg. The style for the DataGridCells is as follows:
<Style x:Key="DataGridCellStyle" TargetType="{x:Type DataGridCell}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{StaticResource SelectedBrush}" />
<Setter Property="TextElement.Foreground" Value="#111111" />
</Trigger>
</Style.Triggers>
<Setter Property="Background" Value="Transparent" />
<Setter Property="TextElement.Foreground" Value="#666666" />
<Setter Property="BorderBrush" Value="Transparent" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border Background="Transparent"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="0"
SnapsToDevicePixels="True"
Padding="5"
VerticalAlignment="Center">
<ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
This added template does basically exactly what I want in terms of how it should be displayed. However there is an issue. When the user clicks on any cell to highlight the row, they must click within the border that is set in the style to actually get the DataGrid to highlight the row.
Using Snoop I am able to see that it is the border causing the issue. This: https://i.sstatic.net/FZzzZ.jpg is what Snoop shows as the border, and unless my mouse is on or in the red highlighted line when clicked, the row will not be selected/highlighted.
Is there any way I can modify my template to allow for it to highlight the row when any part of the cell is clicked and not just within the border?
Or alternatively, is there some easy way I can vertically center the text in my cells?
I have already tried setting TextElement.VerticalAlignment
in my style, but this causes there to be some extra lines within the datagrid that look weird.
Border in template doesn't fill available DataGridCell space because it is centered (VerticalAlignment="Center"
)
if you set VerticalAlignment="Center"
only for ContentPresenter and VerticalAlignment="Stretch"
and HorizontalAlignment="Stretch"
for Border, it should work.
it is even better to configurate alignment in style (with style)
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Border ...>
<ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}" ... />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>