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

Yan Cui

I help clients go faster for less using serverless technologies.

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

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

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

 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


7 thoughts on “WPF – how to bind ScaleTransform to Slider, percentage style!”

  1. Im using RenderTransformOrigin=”0.5, 0.5″ to scale from the center of the image. This works except the image grows in size and covers all my other controls. Do I need to clip the image or is there an easier way?

Leave a Comment

Your email address will not be published. Required fields are marked *