WPF DataGrid Column Alignment

Feb 12, 2009 at 2:40 PM
How do you align column data in WPF DataGrid?  I have the following code below and seems to work for Right alignment, but Center will not work.  Any solutions?

<wpftk:DataGridTextColumn Header="Cost ( $ )"
                                                Width="70" 
                                                Binding="{Binding Cost, StringFormat=\{0:0.00\}}">

<wpftk:DataGridTextColumn.CellStyle>

<Style TargetType="{x:Type wpftk:DataGridCell}">

<Setter Property="HorizontalAlignment" Value="Center

</Style>

</wpftk:DataGridTextColumn.CellStyle>

</wpftk:DataGridTextColumn>

 

 

Feb 12, 2009 at 10:27 PM
Shaggygi

Try this it seems to work for me

<wpftk:DataGridTextColumn.CellStyle>
   <Style TargetType="{x:Type wpftk:DataGridCell}" >
        <Setter Property="TextBlock.TextAlignment" Value="Center" />
        <Setter Property="TextBlock.VerticalAlignment" Value="Center"/>
    </Style>
</wpftk:DataGridTextColumn.CellStyle>
Feb 13, 2009 at 2:03 PM
That did it.  Thanks a bunch.
Jun 4, 2009 at 10:38 AM

<Setter Property="TextBlock.VerticalAlignment" Value="Center"/>   does not work as expected.

That property centers an entire cell rectangle (with grid lines), not a text.

Jun 21, 2010 at 12:06 PM

How do you define the style with HorizontalAlignment Right, if columns are added from codeBehind, AND i want to apply the style ONLY to a specific columnType e.g. DataGridDoubleColumn?

My workaround sets the style in code behind (analogous to this post http://wpf.codeplex.com/Thread/View.aspx?ThreadId=75433 ) but perhaps there is a way to do it in XAML.

-------------

The following xaml applys the style to all Columns, but I don't know how to restrict it to DataGridDoubleColumn:

<DataGrid:ThemedDataGrid.CellStyle>
      <Style TargetType="{x:Type wpftoolkit:DataGridCell}">
        <Setter Property="HorizontalAlignment" Value="Right" />
      </Style>
</DataGrid:ThemedDataGrid.CellStyle>

-------------

Unfortunately I cannot define the columns in xaml. This would be easy:

   

<DataGrid:ThemedDataGrid.Columns>

      <DataGrid1:DataGridDoubleColumn x:Name="aa"
                                      IsReadOnly="True"
                                      Binding="{Binding Double}" >

        <DataGrid1:DataGridDoubleColumn.CellStyle>
          <Style TargetType="{x:Type wpftoolkit:DataGridCell}">
            <Setter Property="HorizontalAlignment" Value="Right" />
          </Style>
        </DataGrid1:DataGridDoubleColumn.CellStyle>
        
      </DataGrid1:DataGridDoubleColumn>

      <wpftoolkit:DataGridTextColumn Binding="{Binding SocialSecurity}"/>
           
    </DataGrid:ThemedDataGrid.Columns>