WPF ScaleTransform Direction

June 28th, 2007 by ryan Leave a reply »

The key to scaling your WPF elements in a specific direction other than down and to the right are the CenterX and CenterY properties of the ScaleTransform.  It’s easy enough to set these manually, but that’s just lazy and asking for long term trouble.  Instead, decide how you want it to animate and bind it to something.  For instance, I have a touch screen keyboard I’m working on that I’d like to animate Up and to the Right when you are holding down the key.  Here’s how I did it:

<Page xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
  <Button Margin="5,5,5,5" Width="50" Height="50" x:Name="btnKey">
    My Button
    <Button.RenderTransform>
      <ScaleTransform x:Name="buttonscale" ScaleX="1" ScaleY="1" CenterX="0" CenterY="{Binding ElementName=btnKey, Path=ActualHeight}" />
    </Button.RenderTransform>
    <Button.Triggers>
      <EventTrigger RoutedEvent="Button.Click">
        <BeginStoryboard>
          <Storyboard>
            <DoubleAnimation Storyboard.TargetName="buttonscale" Storyboard.TargetProperty="(ScaleTransform.ScaleX)" To="1.5" Duration="0:0:0.25" AutoReverse="True"/>
            <DoubleAnimation Storyboard.TargetName="buttonscale" Storyboard.TargetProperty="(ScaleTransform.ScaleY)" To="1.5" Duration="0:0:0.25" AutoReverse="True"/>
          </Storyboard>
        </BeginStoryboard>
      </EventTrigger>
    </Button.Triggers>
  </Button>
</Page>

The key is that I bound the CenterX proeprty to the button’s ActualHeight property.  If you wanted to scale from some midpoint though, you’ll have to specify a Converter in your bind syntax.  This Converter technique is often cited in the ubiquitous “Reflection trick”.

Advertisement

2 comments

  1. Eibi says:

    Hello,

    Say, is it possible to decide witch filter to use in the scale-transform (zoom)? bilinear\bicubic etc. ?

    Thanks

  2. cromwellryan says:

    To be honest, I don’t know. I would suggest looking to the MSDN forum for WPF: http://social.msdn.microsoft.com/Forums/en-US/wpf/threads/

Leave a Reply