WPF TextBlock字体调整大小以填充网格中的可用空间

Nat*_*ugg 50 wpf fonts resize textblock

我有一些文本在运行时显示在文本块中.我希望字体大小可以填充给定的区域.我认为我已正确设置文本块以"自动调整大小",我尝试增加字体大小,直到文本块大于其父级,然后将字体大小减小1.问题是我无法控制重绘/重新计算它的大小.

这是更好的方法吗?或者有没有办法让我的方法有效?

Job*_*Joy 70

把TextBlock里面包裹起来ViewBox:

   <Grid>
    <Viewbox>
        <TextBlock TextWrapping="Wrap" Text="Some Text" />
    </Viewbox>
   </Grid>
Run Code Online (Sandbox Code Playgroud)

  • 这填补了所有水平空间......但是如何对垂直空间也这样做呢?我无法包装文本块文本,直到它获得非常小的字体大小. (7认同)
  • 不赞成投票的是,Textwrapping不适用于viewbox,除非设置了textblock的宽度,这违反了viewbox的整个思想。 (3认同)

小智 31

我有同样的问题.你可以用它来调整大小的字体大小的的文本块,以填补该地区时有溢出.


<Viewbox StretchDirection="DownOnly" Stretch="Uniform">
    <TextBlock Text="{Binding Path=Title}" HorizontalAlignment="Center"/>
</Viewbox>
Run Code Online (Sandbox Code Playgroud)

  • 哇,我花了好几个小时尝试使用Measure方法和Width,ActualWidth,RenderWidth找到类似问题的解决方案,但没有任何工作ahahahahahahah我从未发现过"DownOnly"属性,谢谢!:) (3认同)
  • 如果您希望字体变窄而不是变小,您可以将“拉伸”值更改为“填充”。 (2认同)

Nat*_*ugg 9

我找到了一个很好的方法来使用ViewBox:

 <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
        <RowDefinition Height="50" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="100" />
    </Grid.ColumnDefinitions>
    <Viewbox Grid.Row="0" Grid.Column="0" Stretch="Uniform">
        <TextBlock Name="tbTest" Background="Yellow" Text="This is some text" />    
    </Viewbox>

    <ContentControl Grid.Column="0" Grid.Row="2">
        <TextBlock>This is some text</TextBlock>
    </ContentControl>
</Grid>
Run Code Online (Sandbox Code Playgroud)


小智 8

WPF ViewBox控件可以通过其内容增长/缩小到可用空间.

只需将你TextBlock放在一个ViewBox;

<Viewbox Stretch="Uniform" Width="50" Height="50">
    <TextBlock Text="Test" />
</Viewbox>
Run Code Online (Sandbox Code Playgroud)

ViewBox 通常由其容器缩放.