Canvas 会覆盖其内部 TextBlock 的 TextAlignment 值
我正在尝试配置作为 Canvas 子级的 TextBlock 的 TextAlignment。我意识到在网格中 TextAlignment 可以工作,但是在 Canvas 中你不能将其配置为 Center。
我真的希望有人能够帮助并阐明这个主题。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个相对简单的解决方案是将 TextBlock 包装在具有一定宽度的 StackPanel 中,并将 TextBlock 的 HorizontalAlignment 设置为 Center。这将使 StackPanel 中的文本居中。
宽度是重要的部分。如果没有宽度,TextBlock 将不知道它有多少空间,因此也不知道如何将其自身居中。
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.
画布将始终为其子元素提供“所需的大小”。因此,如果您的 TextBlock 需要 100 像素宽才能显示其文本,那么 Canvas 将为它提供正好 100 像素的宽度。另一方面,网格可以根据 TextBlock 所在的列/行为 TextBlock 提供更多或更少的空间。
对于单行文本(即没有新行),TextAlignment 唯一发挥作用的时间是 TextBlock 处于给予比其需要更多(或更少,如果启用 TextWrapping)的空间。
对于多行文本(或者在文本换行的情况下),TextAlignment 会将其文本与 TextBlock 的边界对齐。
由于 Canvas 永远不会强制 TextBlock 换行,因此 TextAlignment 唯一发挥作用的时候是多行文本。
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.