How to change text alignment Autogeneratedcolumn

I am trying to figure out how to change the text alignment of an automatically 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
+4
source share
3 answers

So what I ended up doing is customize the 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 this style in code.

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
+2
source

, / , . , , , .

, #, - VB, , , .

, , , , :

WPF DataGrid

Style rightStyle = new Style { TargetType = typeof(DataGridCell) };
style.Setters.Add(new Setter(Control.HorizontalAlignmentProperty, HorizontalAlignment.Right));

CellStyle , ,

dataGridTextColumn.CellStyle = style;

, ... , .

, , ..

I am not going to take it for granted, I just took the code that others published and collected various fragments. I just finally received a small contribution to offer a site that was extremely useful to me in my own attempts to figure out this .NET material, so I want to offer it.

0
source

All Articles