2

I have two TextBlocks, each with a different font size, and am trying to align them vertically so that their baselines match up.

I know how to do this by creating multiple Run elements within a single TextBlock, but in this case my TextBlocks are not directly adjacent, so that won't work. Here's a simplified example of my layout:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="100"></ColumnDefinition>
    <ColumnDefinition Width="200"></ColumnDefinition>
  </Grid.ColumnDefinitions>
  <Grid.RowDefinitions>
    <RowDefinition Height="100"></RowDefinition>
  </Grid.RowDefinitions>
  <TextBlock Grid.Column="0" 
             FontSize="20" 
             VerticalAlignment="Bottom">Small</TextBlock>
  <TextBlock Grid.Column="1"                  
             FontSize="50" 
             VerticalAlignment="Bottom">Large</TextBlock>
</Grid>

If I could find a way to calculate the baseline of the font in code, that would be good enough - I could do the alignment in code, using a Canvas or custom Panel - but I haven't been able to find any WP7 APIs for finding font metrics.

I have found a very similar question here, but the solution involves the FormattedText class, and unfortunately this is not available on WP7.

I would really like to be able to do this without hardcoding any margins/offsets, if possible.

2 Answers 2

3

Whilst I agree with Matt's answer, if you actually need to solve the problem without manually setting margins, etc, then you can align them "properly" by setting the LineHeight to the tallest line, and then setting LineStackingStrategy to BlockLineHeight.

2
  • How do you get the tallest line?
    – tofutim
    Jun 10, 2011 at 20:49
  • @tofutim I was assuming that you know yourself which line is designed to be tallest. If you're using one of the built-in styles, you can use the static resource for the matching font size. Jun 13, 2011 at 10:12
-1

In that you are hardcoding the fontsizes in XAML, what's so bad about hardcoding margins to create the effect you are looking for?

This will also mean that you only need to do the calcuation once, rather than forcing the app to do it every time the page is laid out.

3
  • I'd like to be able to change the font sizes depending on the screen resolution / orientation.
    – Nick
    Jun 3, 2011 at 11:28
  • As there is only one supported resolution and 2 orientations then that's only needing to do it twice.
    – Matt Lacey
    Jun 3, 2011 at 12:18
  • 2
    Thanks Matt, that's probably reasonable. The reason I ask is that I have existing layout code that can scale to any resolution on other platforms (iOS/Android). I was hoping to avoid making assumptions about future supported screen resolutions on WP7 too.
    – Nick
    Jun 3, 2011 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.