为什么Cell Header和Cell内容未在datagrid中对齐?

时间:2014-01-22 10:51:30

标签: c# wpf xaml datagrid

我有这个xaml代码:

            <DataGridTextColumn Header="number" Binding="{Binding Path=Number, Mode=OneWay}" Width="70"  CanUserResize="False" >
                <DataGridTextColumn.CellStyle>
                    <Style>
                        <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center" />
                    </Style>
                </DataGridTextColumn.CellStyle>
            </DataGridTextColumn>

            <DataGridTextColumn Header="Status" Binding="{Binding Path=ProcessingState}" Width="100">
                <DataGridTextColumn.CellStyle>
                    <Style>
                        <Setter Property="FrameworkElement.HorizontalAlignment" Value="Center" />
                    </Style>
                </DataGridTextColumn.CellStyle>


            </DataGridTextColumn>

但是当它在屏幕上显示时,它会生成以下视图:

enter image description here

可以看出,细胞未与标题对齐。我怎样才能使它们对齐?

1 个答案:

答案 0 :(得分:2)

如果您只想将文本放在单元格中心,那么您可以使用DataGridTemplateColumn这样的内容:

<DataGrid ItemsSource="{Binding SalesPeriods}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="number" Width="70" CanUserResize="False">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=Number, Mode=OneWay}" 
                        HorizontalAlignment="Center" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Status" Width="100">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=ProcessingState, Mode=OneWay}" 
                        HorizontalAlignment="Center" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

如果您更喜欢使用DataGridTextColumn,那么您仍然可以使用ElementStyle属性实现此目标:

<DataGridTextColumn Header="number" Binding="{Binding Path=Year, Mode=OneWay}" 
    Width="70" CanUserResize="False" >
    <DataGridTextColumn.ElementStyle>
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="HorizontalAlignment" Value="Center" />
        </Style>
    </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>