How to use the RenderTransform to control the orientation of a TextBlock

ellic picture ellic · Mar 5, 2012 · Viewed 7k times · Source

I want to make a TextBlock shown vertically, just like the username in the Windows Phone built-in email app:

enter image description here

And my XAML code is:

<Grid x:Name="LayoutRoot">
    <Grid.Background>
        <ImageBrush ImageSource="{StaticResource Status_Background}" Stretch="UniformToFill"/>
    </Grid.Background>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="80"/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <ProgressBar x:Name="progressBar" IsIndeterminate="True" Grid.ColumnSpan="2" VerticalAlignment="Top" Visibility="Collapsed" Margin="0,6"/>
    <StackPanel>
        <Image x:Name="headerImage" Margin="0,12"  Width="70" Height="70" HorizontalAlignment="Center" Stretch="UniformToFill"/>
        <TextBlock Text="userName" x:Name="userName" Grid.ColumnSpan="2" Margin="0" 
                   FontSize="50" Foreground="{StaticResource Status_UserName}"
                   Width="Auto" HorizontalAlignment="Left" VerticalAlignment="Bottom">
            <TextBlock.RenderTransform>
                <RotateTransform Angle="-90" CenterX="80" CenterY="70"/>        
            </TextBlock.RenderTransform>
        </TextBlock>
    </StackPanel>
    <ScrollViewer Grid.Column="1" Height="Auto">
    </ScrollViewer>
</Grid>

The result is:

enter image description here

The TextBlock didn't show up in the right place, how could I modify the XAML code? Thanks in advance.

Answer

ColinE picture ColinE · Mar 5, 2012

Your problem is that render transforms are applied after layout, as described in this blog post. You need to bring your TextBlock out of the StackPanel and ensure that it is in the top left of the screen, then rotate it.

<Grid x:Name="LayoutRoot" >
    <Grid.Background>
        <ImageBrush ImageSource="{StaticResource Status_Background}" Stretch="UniformToFill"/>
    </Grid.Background>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="80"/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>

    <TextBlock Text="userName" x:Name="userName" FontSize="50"  Foreground="{StaticResource Status_UserName}" Width="auto"
               HorizontalAlignment="Left" VerticalAlignment="Bottom">
             <TextBlock.RenderTransform>
               <RotateTransform Angle="-90" CenterX="80" CenterY="70"/>        
          </TextBlock.RenderTransform>
    </TextBlock>

    <ProgressBar x:Name="progressBar" IsIndeterminate="True" Grid.ColumnSpan="2" VerticalAlignment="Top" Visibility="Collapsed" Margin="0,6" />
    <StackPanel>
        <Image x:Name="headerImage" Margin="0,12"  Width="70" Height="70" HorizontalAlignment="Center" Stretch="UniformToFill"/>            
    </StackPanel>
    <ScrollViewer Grid.Column="1" Height="auto">

    </ScrollViewer>
</Grid>