This is the fourth post in the series of looking at Transforms in Silverlight. The first post looked at RotateTransform, the second SkewTransform and the third examined ScaleTransform.
This post will look at the easiest of the transforms the TranslateTransform.
The TranslateTransform takes the element you apply it to and draws it in another position determined by a set of x and y coordinates.
The transform is applied from a central point which is defaulted to 0 on the x-axis and 0 on the y-axis. This default point is the top left of the element.
1. Setting up the project.
For this example I am using a button that is centred in a 400x400 grid. A red semi-transparent rectangle has been placed over the button to show the original position once the transform has been applied to the button.
Transforms can’t just defined directly to the element, you must add it to the RenderTransform property of the element. To do this you must use the element-property syntax in the XAML to set the transform since it is a complex property. Then you can add the base definition for the transform.
2. The X and Y properties.
2a. Setting X.
When you give the X property of the translatetransform a value your element will move along the x-axis, to the left or right, from its original position.
You can use both positive and negative numbers as a value for the X property.
Above I have set the value to X to 50 and when the project is run the button is drawn 50 points to the right of its original position.
2b. Setting Y.
As you would expect giving a value to the Y property will move the element along the y-axis which will draw the element up or down from its starting position.
A positive value, like the example above, draws the button lower and a negative value would have moved the button up.
2c. Setting X and Y.
If you want to re-draw your element in both directions all that is needed to give values to both the X and Y properties.
Positive values draws the element down and to the right.
Setting the values to negative numbers does the opposite.
The element is drawn up and to the left.
3. Resizable element and RenderTransformOrigin.
With the nature of Silverlight being resolution independent it is possible that your element may not always be the same size and therefore you will not want to set only the X and Y properties.
In the case that you want to redraw your element, and it is possible that the element may change size, you need to set the RenderTransformOrigin property of the element.
The x and y coordinates values of the rendertransformorigin range from 0 to 1 and run from the top left corner of the element, position 0,0, and move to the lower right corner, position 1,1.
Using rendertrnasformorigin guarantees that your element will be drawn where you want it regardless of its size.