I am trying to center the text in the cells for a SfDataGrid in UWP. The columns are bound during runtime so I can not set a cell style on column elements.
The xaml for the grid looks like this:
<grid:SfDataGrid Name="GridData"
AlternatingRowStyle="{StaticResource mainTableRowStyle}"
RowStyle="{StaticResource mainTableRowStyle}"
HeaderStyle="{StaticResource headerStyle}"
Foreground="WhiteSmoke"
framework:FocusExtension.IsFocused="{Binding Focused}"
AllowSelectionOnPointerPressed="True"
Grid.Row="0"
Columns="{Binding SfGridColumns, Mode=TwoWay}"
AutoGenerateColumns="True"
IsDynamicItemsSource="True"
ItemsSource="{Binding ElementName=dataPager,Path=PagedSource}"
ColumnSizer="Star"
AllowSorting="False"
SelectedItem="{Binding SelectedGridItem, Mode =TwoWay, UpdateSourceTrigger=PropertyChanged}">
<interactivity:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="Holding">
<core:InvokeCommandAction Command="{Binding HoldCommand}" />
</core:EventTriggerBehavior>
</interactivity:Interaction.Behaviors>
</grid:SfDataGrid>
I have tried to add a style to the cells in order to align the text:
<Style x:Key="cellStyle" TargetType="grid:GridCell">
<Setter Property="FontSize" Value="20" />
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="FontWeight" Value="Bold" />
</Style>
<!-- CellStyle="{StaticResource cellStyle}" -->
But that doesn't help because it centers the entire cell and the inner borders of the grid are disrupted. (looks something like the below picture)
I want just the text inside the cell to be aligned. (also tried the HorizontalContentAlignment center, it didn't do anything)
Finally, I have tried to rewrite the template of the cell. The SfDataGrid does not have a CellTemplate property, but it has a GridCellTemplateSelector property. So, I have created a template like this:
<framework:GridCellTemplateSelector x:Key="templateSelector"/>
<DataTemplate x:Key="CellTemplate1">
<TextBlock Foreground="DarkBlue" Text="{Binding}" HorizontalAlignment="Center"/>
</DataTemplate> <!-- and added CellTemplateSelector="{StaticResource templateSelector}" to the grid -->
public class GridCellTemplateSelector : DataTemplateSelector
{
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
return Application.Current.Resources["CellTemplate1"] as DataTemplate;
}
}
This one doesn't work also because it seems the method in GridCellTemplateSelector is not hit. I am thinking if I could make the CellTemplateSelector to work I could achieve my objective.
