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

Time:09-21

I need to change the font size of a label programmatically. The label is located inside a 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>

The font size of text inside the label is assumed to be 24. However, even if I set it in my code like this to its 'original' value in xaml:

label1.FontSize = 24;

it becomes smaller.

Is there a simple way to keep the ratio between the new font size and the scale factor of the Viewbox?

CodePudding user response:

You can try to set ViewBox.StretchDirection property to DownOnly, for the label will be smaller, but not bigger:

<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>

So the code results to :
viewbox scaling

  • Related