looking for some solutions? You are welcome.

SOLVED: Center text using Synchfusion's SfDataGrid for UWP with dynamic columns


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}"
                                     framework:FocusExtension.IsFocused="{Binding Focused}"
                                     Columns="{Binding SfGridColumns, Mode=TwoWay}"
                                     ItemsSource="{Binding ElementName=dataPager,Path=PagedSource}"
                                     SelectedItem="{Binding SelectedGridItem, Mode =TwoWay, UpdateSourceTrigger=PropertyChanged}">
                            <core:EventTriggerBehavior EventName="Holding">
                                <core:InvokeCommandAction Command="{Binding HoldCommand}" />

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" />
   <!-- 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)

enter image description here

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.

Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots

No comments: