Pages

Tuesday 31 January 2012

DataGridTextColumn Text Alignment (improved)

From Martin: I’ve been using this technique DataGridTextColumn Text Alignment, but I found it had 2 weird effects which I ran by Katharine yesterday.

1. If you clicked on the row just to the left of the value, it wasn’t registering and selecting the row
2. When the row was selected, the value was highlighted weirdly in a dark blue “selected” box

Apparently, that approach was overwriting the usual cell style template and making the textblock behave a little strangely.
With the ElementStyle change she suggested, the 2 issues above went away, so it seems to be the right way to do it.

Courtesy of Katharine, this is the correct way:
<DataGridTextColumn Header="Blah" Binding="{Binding Blah}">
   <DataGridTextColumn.ElementStyle>
      <Style TargetType="{x:Type TextBlock}">
         <Setter Property="TextAlignment" Value="Right" />
      </Style>
   </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
Alternatively the style can be set up as StaticResource if it needs to be referenced by several DataGrid columns.

<Style x:Key="rightAlignedColumn" TargetType="{x:Type TextBlock}">
   <Setter Property="TextAlignment" Value="Right" />
</Style>

...

<DataGridTextColumn Header="Blah"
                    Binding="{Binding Blah}"
                    ElementStyle="{StaticResource rightAlignedColumn}">
</DataGridTextColumn>