Graeme
Graeme

Reputation: 2685

WPF - Can't right-align a TextBlock when using StringFormat

I have a TextBlock within a GridViewColumn. I format to currency using StringFormat. This causes the field to be left aligned. I can't get it right aligned. Tried HorizontalAlignment and TextAlignment but nothing works.

<TextBlock HorizontalAlignment="Right" Text="{Binding Path=Amount, StringFormat={}{0:€ # ##0}}" />
<TextBlock TextAlignment="Right" Text="{Binding Path=Amount, StringFormat={}{0:€ # ##0}}" />

If I do this from this post, it works but right aligns all columns. I want numbers right aligned, dates centre and text left.

<ListView.Resources>  
    <Style TargetType="ListViewItem">  
        <Setter Property="HorizontalContentAlignment" Value="Right" />  
    </Style>
</ListView.Resources>

Any clues please?

Upvotes: 1

Views: 2539

Answers (2)

Rohit Vats
Rohit Vats

Reputation: 81253

Set HorizontalContentAlignment to Stretch. This will work:

<ListView>
   <ListView.Resources>
      <Style TargetType="ListViewItem">
         <Setter Property="HorizontalContentAlignment" Value="Stretch" />
      </Style>
   </ListView.Resources>
   <ListView.View>
      <GridView>
         <GridViewColumn>
            <GridViewColumn.CellTemplate>
               <DataTemplate>
                  <TextBlock HorizontalAlignment="Right"
                       Text="{Binding Path=Amount, StringFormat={}{0:€ # ##0}}"/>
               </DataTemplate>
            </GridViewColumn.CellTemplate>
         </GridViewColumn>
      </GridView>
   </ListView.View>
 </ListView>

Upvotes: 2

Joel Lucsy
Joel Lucsy

Reputation: 8706

Change your resource to HorizontalContentAlignment to Stretch, this will allow the contents of each cell in the ListView to take up the entire space. Then your HorizontalAlignment attributes will work.

Upvotes: 0

Related Questions