0

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)

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.

1 Answer 1

1

The 'GridCellTemplateSelector' is not for your scenario. The sfDataGrid has 'CellTemplate', it's available for the columns.

I made a code sample for your reference:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <syncfusion:SfDataGrid x:Name="dataGrid"
                           ItemsSource="{Binding Orders}">
    </syncfusion:SfDataGrid>
</Grid>
public class OrderInfo
{
    int orderID;
    string customerId;
    string customerName;

    public int OrderID
    {
        get { return orderID; }
        set { orderID = value; }
    }

    public string CustomerID
    {
        get { return customerId; }
        set { customerId = value; }
    }

    public string CustomerName
    {
        get { return customerName; }
        set { customerName = value; }
    }



    public OrderInfo(int orderId, string customerName, string customerId)
    {
        this.OrderID = orderId;
        this.CustomerName = customerName;
        this.CustomerID = customerId;
    }
}
public sealed partial class MainPage : Page
{
    private ObservableCollection<OrderInfo> _orders;

    public ObservableCollection<OrderInfo> Orders
    {
        get { return _orders; }
        set { _orders = value; }
    }

    public MainPage()
    {
        this.InitializeComponent();
        _orders = new ObservableCollection<OrderInfo>();
        this.GenerateOrders();
        this.DataContext = this;
        Type mytype = Orders.FirstOrDefault().GetType();
        foreach (PropertyInfo pi in mytype.GetProperties())
        {
            dataGrid.Columns.Add(new GridTextColumn() { MappingName = pi.Name, TextAlignment = TextAlignment.Center, HeaderText = pi.Name });
        }
    }

    private void GenerateOrders()
    {
        _orders.Add(new OrderInfo(1001, "Maria Anders",  "ALFKI"));
        _orders.Add(new OrderInfo(1002, "Ana Trujillo",  "ANATR"));
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the example. But, as I have described in the question, the columns are dynamic and bound during runtime which is why I couldn't use something similar with this example. This is a generic grid that can have one, two, or more columns depending on the data. I want a way to align center all the contents in all columns.
Inspired by your response I have managed to solve it by setting the TextAlignment property from code when I was creating the columns. can you please update your response with something like {for (var i = 0; i < items.Count; i++) SfGridColumns.Add(new GridTextColumn { MappingName = "Collection[" + i + "].DisplayValue", TextAlignment = TextAlignment.Center, HeaderText = Headers[i].Name } );} In order to mark it as the answer?
@Cosmin I also find this strange behavior. If I set 'TextAlignment' in XAML style, it will be override. I've updated my reply.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.