开发者

Align TextBlocks by baseline

开发者 https://www.devze.com 2023-03-10 00:19 出处:网络
I have two TextBlocks, each with a different font size, and am trying to align them vertically so that their baselines match up.

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 findin开发者_运维知识库g 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消