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.

Community
  • 1
  • 1
Nick
  • 23
  • 3

2 Answers2

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.

Derek Lakin
  • 16,179
  • 36
  • 51
  • How do you get the tallest line? – tofutim Jun 10 '11 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. – Derek Lakin Jun 13 '11 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.

Matt Lacey
  • 65,560
  • 11
  • 91
  • 143
  • I'd like to be able to change the font sizes depending on the screen resolution / orientation. – Nick Jun 03 '11 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 03 '11 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 03 '11 at 13:50