BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Transforms - Translate

The one hundred and forty-second part of the Windows Presentation Foundation Fundamentals tutorial examines the second two-dimensional transform provided by WPF. This is the translate transform, which relocates a control.

TranslateTransform

The second of the standard WPF transforms is provided by the TranslateTransform class. This simple transform allows you to move a control horizontally and vertically. Although a basic operation, it can be very useful when animating controls and other user interface elements. For example, you can make controls slide when the mouse pointer is positioned above them, perhaps bringing elements of a control into view that were previously hidden. In this article we'll look only at the basic transform. Animation will be covered in a later instalment.

To demonstrate the transform we need a sample project. Create a new WPF application in Visual Studio, naming the solution, "TranslateTransformDemo". Once ready, replace the XAML in the main window with the code below:

<Window x:Class="TranslateTransformDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Transform Demo" Height="150" Width="250">
    <StackPanel>
        <Button Width="100" Height="25" Content="Standard"/>
        <Button Width="100" Height="25" Content="Translated"/>
    </StackPanel>
</Window>

The window includes two Buttons arranged using a StackPanel. Using the standard layout of their parent means that the buttons appear one above the other.

WPF TranslateTransform Demo Window

Applying a TranslateTransform

TranslateTransform is applied in the same manner as the transform we've seen earlier. It has two properties, X and Y, which specify the distance to move the control to the right and downwards respectively. You can specify a negative value to move the control in the opposite direction.

Adjust the XAML for the second button to add a transform, as follows:

<Button Width="100" Height="25" Content="Translated">
    <Button.RenderTransform>
        <TranslateTransform X="-50" Y="10"/>
    </Button.RenderTransform>
</Button>

The second button is moved fifty device-independent units to the left and ten units down, as shown below:

WPF TranslateTransform

9 March 2015