Canvas overrides the TextAlignment value of TextBlock inside it
I am trying to configure the TextAlignment of a TextBlock that is a child of a Canvas. I realized that in a grid the TextAlignment works, but when in a Canvas you can't configure it as Center.
I really hope someone could help and shed some light on this 开发者_运维百科topic.
A relatively easy solution is to wrap your TextBlock in a StackPanel with a width, and set the TextBlock's HorizontalAlignment to Center. This will center the text in the StackPanel.
The Width is the important part. Without the Width, the TextBlock wouldn't know how much room it has, and therefore how to center itself.
The Canvas will always give it's child elements their "desired size". So if your TextBlock needs to be 100 pixels wide to display it's text, then the Canvas will give it exactly 100 pixels. A Grid on the other hand, can give the TextBlock more or less space depending on what column/row the TextBlock is in.
For single lines of text (i.e. no new lines), the only time TextAlignment comes into play is when the TextBlock is given more (or less if TextWrapping is enabled) space than it needs.
For multiple lines of text (or in the case of text wrapping a single line), then the TextAlignment will align it's text withing the bounds of the TextBlock.
Since a Canvas will never force a TextBlock to wrap, the only time TextAlignment comes into play there is with multiple lines of text.
<Canvas Width="300" Height="50">
<TextBlock Canvas.Top="0" TextAlignment="Center">
This will not center
</TextBlock>
<TextBlock Canvas.Top="25" TextAlignment="Center">
This will center the shorter<LineBreak />lines of text
</TextBlock>
</Canvas>
精彩评论