Elentok's Blog

About me

WPF: Align text to the right

Aligning text to the right... sounds like a simple thing to do, apparently not that simple.

First, you have to define a CellTemplate and a DataTemplate for the GridViewColumn with an internal TextBlock that has it's HorizontalAlignment property set to Right:

<GridViewColumn Header="Size" Width="80">
  <GridViewColumn.CellTemplate>
    <DataTemplate>
      <TextBlock HorizontalAlignment="Right"
                 Text="{Binding Size}" />
    </DataTemplate>
  </GridViewColumn.CellTemplate>
</GridViewColumn>

Then you have to add a style resource to set the HorizontalContentAlignment property of ListViewItem elements to Stretch:

<Style TargetType="{x:Type ListViewItem}">
  <Setter Property="HorizontalContentAlignment" 
          Value="Stretch"></Setter>
</Style>

I can understand why it's like this though, basically you can put anything in those cells, and in some cases the alignment flag might not have any meaning... although it would have been very nice for the more simple apps...

Next:WPF, ImageSource and Embedded Resources