#741 – Using Touch Manipulation Events to Translate an Element

You can use the touch manipulation events to translate an element, that is, to move it around on the screen.

To start with, you set the IsManipulationEnabled property of the element to true.  This allows the manipulation events to be fired.  You also handle both the ManipulationStarting and ManipulationDelta events.

    <Canvas Name="canvMain" Background="Transparent">
        <Image Source="JamesII.jpg" Width="100"
               IsManipulationEnabled="True"
               RenderTransform="{Binding ImageTransform}"
               ManipulationStarting="Image_ManipulationStarting" ManipulationDelta="Image_ManipulationDelta"/>
    </Canvas>

Below is the code that allows the image to be moved around (translated) as the user moves their finger.  We bind the image’s render transform to a MatrixTransform object, which contains a matrix that allows us to scale, rotate or translate the image.  In our case, we modify the translation part of the matrix with the translation vector returned in the ManipulationDelta event.

    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;

            ImageTransform = new MatrixTransform();
        }

        private MatrixTransform imageTransform;
        public MatrixTransform ImageTransform
        {
            get { return imageTransform; }
            set
            {
                if (value != imageTransform)
                {
                    imageTransform = value;
                    RaisePropertyChanged("ImageTransform");
                }
            }
        }

        private void Image_ManipulationStarting(object sender, ManipulationStartingEventArgs e)
        {
            // Ask for manipulations to be reported relative to the canvas
            e.ManipulationContainer = canvMain;
        }

        private void Image_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            ManipulationDelta md = e.DeltaManipulation;
            Vector trans = md.Translation;

            // Update matrix to reflect translation
            Matrix m = imageTransform.Matrix;
            m.Translate(trans.X, trans.Y);
            imageTransform.Matrix = m;
            RaisePropertyChanged("ImageTransform");

            e.Handled = true;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string prop)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

741-001