在 Viewbox 中以编程方式更改元素的字体大小很奇怪

Changing the font size of an element programmatically inside a Viewbox works weird

我需要以编程方式更改标签的字体大小。标签位于 Viewbox 内:

<Window ...
        FontSize="24"
        HorizontalAlignment="Center" VerticalAlignment="Center"
        WindowStyle="ThreeDBorderWindow"
        ResizeMode="NoResize">
    <Grid>
        <Viewbox x:Name="vb" Stretch="Uniform">
            <Label x:Name="label1" HorizontalContentAlignment="Center" Content="Text"/>
        </Viewbox>
    </Grid>
</Window>

标签内文本的字体大小假定为 24。但是,即使我在我的代码中将其设置为 xaml 中的 'original' 值:

label1.FontSize = 24;

变小了

有没有一种简单的方法来保持新字体大小与 Viewbox 的比例因子之间的比例?

你可以试试把ViewBox.StretchDirection属性设置成DownOnly,标签会变小,但不会变大:

<StackPanel Width="200" >
   <Label Content="Text" FontSize="24" HorizontalAlignment="Center"/>
   <Viewbox StretchDirection="DownOnly" Stretch="Uniform">
      <Label Content="Text" FontSize="24"/>
   </Viewbox>
   <Viewbox StretchDirection="DownOnly" Stretch="Uniform">
      <Label Content="ABCDEF EEEEE ABCDEFGJKLMNOP" FontSize="24"/>
   </Viewbox>
</StackPanel>

所以代码结果为: