Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I was wondering if anyone had an easy way to get the text in a WPF data grid to be center aligned. I got the data grid to work just fine, but the right text alignment bothered me. I goggled some, and downloaded the wpftoolkit, but the examples either do not work, or give me a compile error. I did add the reference to the wpftoolkit to my project. Any help would be appreciated. Thank you

the xaml for the data grid is as follows

<WpfToolkit:DataGrid AutoGenerateColumns="True" Margin="15,15,10,65" Name="DG1" CanUserReorderColumns="False" />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

If you set the Block.TextAlignment property to Center on the DataGrid, it will be inherited by the TextBlocks and TextBoxes used in DataGridTextColumns and will center the text:

<WpfToolkit:DataGrid
    Block.TextAlignment="Center"
    AutoGenerateColumns="True"
    Margin="15,15,10,65"
    Name="DG1"
    CanUserReorderColumns="False" />

If you want to align text in the cells but not in the headers or elsewhere in the Grid, you can set the property on the DataGridCell using CellStyle:

<WpfToolkit:DataGrid
    AutoGenerateColumns="True"
    Margin="15,15,10,65"
    Name="DG1"
    CanUserReorderColumns="False">
    <WpfToolkit:DataGrid.CellStyle>
        <Style TargetType="WpfToolkit:DataGridCell">
            <Setter Property="Block.TextAlignment" Value="Center"/>
        </Style>
    </WpfToolkit:DataGrid.CellStyle>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...