【问题标题】:How to shrink font size in Textblock to fit width of content AND maintain font aspect ratio如何缩小文本块中的字体大小以适应内容的宽度并保持字体纵横比
【发布时间】:2013-09-05 14:25:12
【问题描述】:

这是交易:我有这行 XAML

<Viewbox Canvas.Left="27" Canvas.Top="479" Width="377" Height="21" Stretch="Fill" 
       StretchDirection="DownOnly" VerticalAlignment="Top" HorizontalAlignment="Left">
  <TextBlock Name="TitleText" TextWrapping="Wrap" TextAlignment="Left" FontSize="14" 
           FontStretch="Normal"  FontStyle="Normal" Foreground="White" Width="377" >some long text here
  </TextBlock>
</Viewbox>

我希望字体按比例缩小以适应内容的高度和宽度。 现在发生的情况是字体缩小了,但 Viewbox 也会水平缩放内容,使文本框的宽度变小。 这是一个例子

Example image

如果我设置 Stretch="Fill" 文本将填充宽度,但只会缩小高度的字体大小,使字体看起来非常难看Like this

是否可以缩小文本以适合框架内,以便使用容器的整个宽度和高度?

【问题讨论】:

  • 听起来您可能只想将文本换行到可用空间的整个宽度,而不更改字体大小?或者,降低字体大小以允许文本适合 而不 缩放整个控件。我不确定Viewbox 是解决此问题的最佳解决方案。
  • 听起来你只需要一个多行TextBox 和一个ScrollBar 对我来说......你的最终用户不会感谢你弄乱文本的大小......它会使其与应用程序中的其余文本不一致,就此而言,每个文本对象(我想)与彼此相比的大小会不一致。

标签: c# wpf xaml wpf-controls textblock


【解决方案1】:

您不能将视图框的 StretchDirection 属性设置为“DownOnly”。此设置会导致内容仅垂直拉伸。

【讨论】:

  • 您好 Jan,感谢您的回复。如果没有DownOnly,那么文本也会增长,它应该只会缩小。
  • 这对于使长字符串适合而不会使已经适合的字符串看起来很奇怪很有用。谢谢!
【解决方案2】:

这是你想要的吗?

<Viewbox Stretch="Uniform">
    <TextBlock Name="TitleText" TextWrapping="Wrap" TextAlignment="Left" FontSize="14" 
       FontStretch="Normal"  FontStyle="Normal" Foreground="White" Width="377">
       some long text here
    </TextBlock>
</Viewbox>

【讨论】:

  • 好吧,然后发生的是 1) 文本不换行,文本仅呈现在一行 2) 因此,文本被缩小到很小的大小所以不幸的是,这并没有工作。我需要设置 TextBlock 的宽度,以便 TextBlock 包裹文本
  • 我以为您会在我的示例中将其他属性添加到 TextBlock... 我只是懒得把它们都放在那里,但我现在有了,所以再给它试试看。
【解决方案3】:

这里有一个使用第二个 ViewBox 的可能解决方案:

<Viewbox Canvas.Left="27" Canvas.Top="479" Width="377" Height="21" Stretch="Fill" 
        StretchDirection="DownOnly" VerticalAlignment="Top" HorizontalAlignment="Left">
   <Viewbox Stretch="Fill" Width="Auto" Height="Auto">
       <TextBlock Name="TitleText" TextWrapping="Wrap" TextAlignment="Left" FontSize="14" 
            FontStretch="Normal"  FontStyle="Normal" Foreground="White" Width="377" >some long  text here
       </TextBlock>
   </Viewbox>
 </Viewbox>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    • 2012-10-06
    • 2019-05-06
    • 2016-05-18
    相关资源
    最近更新 更多