WPF TextBlock字体resize以填充网格中的可用空间

我有一些在运行时显示在文本块中的文本。 我希望字体大小是填充所给区域的最大尺寸。 我认为我有正确的文本块设置“autosize”,我试图增加字体大小,直到文本块比它的父母,然后减less字体大小1.问题是我无法得到控制重绘/重新计算其大小。

是一个更好的方法来做到这一点? 或者有什么方法可以使我的方法工作?

TextBlock包装在ViewBox

  <Grid> <Viewbox> <TextBlock TextWrapping="Wrap" Text="Some Text" /> </Viewbox> </Grid> 

我有同样的问题。 您可以使用它来调整 文本块字体 大小 ,以填充溢出时的区域。


 <Viewbox StretchDirection="DownOnly" Stretch="Uniform"> <TextBlock Text="{Binding Path=Title}" HorizontalAlignment="Center"/> </Viewbox> 

我发现了一个很好的方式来使用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> 

WPF ViewBox控件可以将其内容增长/缩小到可用空间。

只需将您的TextBlock放置在ViewBox中;

 <Viewbox Stretch="Uniform" Width="50" Height="50"> <TextBlock Text="Test" /> </Viewbox> 

ViewBox通常由其容器来缩放。

那么,它不是一个“完美”的答案,但这是一个快速的黑客(你可以把它放入kaxaml并testing出来):

 <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Grid Height="300" Background="green"> <Viewbox> <TextBlock Background="red" Text="Hurr"/> </Viewbox> </Grid> </Page> 

ViewBox将放大任何内容以填充其容器。 问题是, TextBlock ,而它的大小,其文本,填充顶部和底部,你不能摆脱(没有做一些繁重的工作)。 这可能会让你更接近你想要的东西。

为了确保包装,您需要设置TextBlockMaxWidth和/或MaxHeight

 <Viewbox StretchDirection="DownOnly" Stretch="Uniform"> <TextBlock MaxWidth="500" TextWrapping="Wrap" FontSize="30" VerticalAlignment="Center" Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."/>