WPF – how to bind ScaleTransform to Slider, percentage style!

Whilst working on an image view I needed the ability to bind the value of a Slider to a ScaleTransform as a percentage value and at the same time display the value of the slider in a label. So for a zoom range from 1% to 250% you would usually set the Minimum and Maximum property of your Slider to 0.01 and 2.5 respectively, by then you wouldn’t be able to display the zoom value as a percentage, e.g. Zoom 148%.

So to get around this limitation, in the end I used the range 1 to 250 for the Slider and added another ScaleTransform with ScaleX and ScaleY set to 0.01, like this:

<StackPanel x:Name="LayoutRoot" Background="Gray">
    <StackPanel Orientation="Horizontal">
        <TextBlock Margin="5,5,10,5">Zoom</TextBlock>
        <TextBlock Margin="5,5,0,5" Text="{Binding Path=Value, ElementName=sldZoom, Mode=OneWay}"/>
        <TextBlock Margin="0,5">%</TextBlock>

    <Slider x:Name="sldZoom" Orientation="Horizontal" Minimum="1" Maximum="250" Value="100"/>

    <Image Source="bingonet.png" RenderTransformOrigin="0, 0">
                <ScaleTransform ScaleX="0.01" ScaleY="0.01"/>
                        <Binding ElementName="sldZoom" Path="Value" Mode="OneWay"/>
                        <Binding ElementName="sldZoom" Path="Value" Mode="OneWay"/>

Yan Cui

I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.

You can contact me via Email, Twitter and LinkedIn.

Hire me.