Search code examples
wpfxamllabelviewbox

WPF change aligment of label and Viewbox


So i have a label in a viewbox so when the application scales the label will also scale. However the user what to choose to AutoScale via Viewbox or No autoscaling and set the properties for the label itself.

So far i got this:

<Viewbox Name="vb">
    <Label
        Name="lblText"
        Width="{Binding ElementName=Sign, Path=ActualWidth}"
        Height="{Binding ElementName=Sign, Path=ActualHeight}"
        HorizontalAlignment="Stretch"
        VerticalAlignment="Stretch"
        HorizontalContentAlignment="{Binding TextAlignment}"
        VerticalContentAlignment="Center"
        Background="Transparent"
        Content="{Binding ObjectName}"
        FontFamily="{Binding Font_Family}"
        FontSize="{Binding FontSize}"
        Foreground="{Binding FontColor}" />
</Viewbox>

Now to get the label AutoSize i have to set the Width and Height to Auto. However when i do this i cannot longer use the HorizontalContentAlignment because the label is the size of the text. When bound to the viewbox size then i can use it but the AutoSize doesn't work.

I was thinking about a event then when the user changes the `` then a event will fire where i can set the properties of the viewbox and label in code.

So in short i'm looking for a way to create a textholding object that can AutoSize or set by hand.


Solution

  • You could simply set the Stretch property of the Viewbox by a DataTrigger, e.g. on a boolean Autoscale property:

    <Viewbox>
        <Viewbox.Style>
            <Style TargetType="Viewbox">
                <Setter Property="Stretch" Value="None"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Autoscale}" Value="True">
                        <Setter Property="Stretch" Value="Uniform"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Viewbox.Style>
    
        ...
    </Viewbox>