Search code examples
wpfvb.netdatagridalignment

How to change Autogeneratedcolumn text alignment


I am trying to figure out how to change the text alignment of an auto generated column in code.

    Private Sub dgBook_AutoGeneratingColumn(sender As System.Object, e As System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs) Handles dgBook.AutoGeneratingColumn
        If e.PropertyType = GetType(DateTime) Then
            Dim dataGridTextColumn As DataGridTextColumn = TryCast(e.Column, DataGridTextColumn)
            If dataGridTextColumn IsNot Nothing Then
                dataGridTextColumn.Binding.StringFormat = "{0:d}"
            End If
        End If

        If e.PropertyName = "Amount" Then
            Dim dataGridTextColumn As DataGridTextColumn = TryCast(e.Column, DataGridTextColumn)
            If dataGridTextColumn IsNot Nothing Then
                dataGridTextColumn.Binding.StringFormat = "{0:#,##0.00;(#,##0.00)}"
                'I tried the next line for testing but it did not work
                dataGridTextColumn.SetValue(TextBox.TextAlignmentProperty, TextAlignment.Center)
            End If
        End If
     End Sub

Solution

  • So what I ended up doing was setting up a style in the XAML WPF code

    <Window.Resources>
        <Style TargetType="DataGridCell" x:Key="rightAlignCell">
            <Setter Property="HorizontalAlignment" Value="Right"></Setter>
        </Style>
    </Window.Resources>
    

    And then I set the cell style to that style in the code behind.

    Private Sub datagrid1_AutoGeneratingColumn(sender As System.Object, e As System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs) Handles datagrid1.AutoGeneratingColumn
        If e.PropertyName = "Amount" Then
            Dim dataGridTextColumn As DataGridTextColumn = TryCast(e.Column, DataGridTextColumn)
            If dataGridTextColumn IsNot Nothing Then
                dataGridTextColumn.Binding.StringFormat = "{0:#,##0.00;(#,##0.00)}"
            End If
            e.Column.CellStyle = TryCast(FindResource("rightAlignCell"), Style)
        End If
    end sub