当前位置 : 主页 > 编程语言 > c语言 >

wpf – 如何更改Autogenerated列文本对齐方式

来源:互联网 收集:自由互联 发布时间:2021-06-24
我试图找出如何更改代码中自动生成列的文本对齐方式. Private Sub dgBook_AutoGeneratingColumn(sender As System.Object, e As System.Windows.Controls.DataGridAutoGeneratingColumnEventArgs) Handles dgBook.AutoGeneratingColu
我试图找出如何更改代码中自动生成列的文本对齐方式.

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
所以我最终做的是在XAML WPF代码中设置一个样式

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

然后我在后面的代码中将单元格样式设置为该样式.

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
网友评论