Sony Arouje

a programmer's log

Image Positioning in Silverlight

leave a comment »

The below code will give you a basic idea of how dragging and positioning an image inside a Canvas will work.

XAML code

<UserControl x:Class=”EmblemDesigner.MainPage”
    d:DesignHeight=”300″ d:DesignWidth=”400″>

    <Grid x:Name=”LayoutRoot” Background=”White”>
        <Canvas x:Name=”emblemDesign” AllowDrop=”True” Background=”Black” MouseLeftButtonUp=”emblemDesign_MouseLeftButtonUp” MouseMove=”imgEmblem_MouseMove”>
                          <Image x:Name=”imgEmblem” Source=”/Images/One.jpg” Height=”100″ Width=”100″ MouseLeftButtonDown=”imgEmblem_MouseLeftButtonDown”  MouseLeftButtonUp=”imgEmblem_MouseLeftButtonUp”></Image>


Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace EmblemDesigner
    public partial class MainPage : UserControl
        double _imgPosX = 0;
        double _imgPosY = 0;
        double _mousePosX = 0;
        double _mousePosY = 0;
        bool _isLeftMouseDown = false;

        public MainPage()

        private void imgEmblem_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            _isLeftMouseDown = true;
            _imgPosX = imgEmblem.Margin.Top;
            _imgPosY = imgEmblem.Margin.Left;

            _mousePosX = e.GetPosition(imgEmblem).X;
            _mousePosY = e.GetPosition(imgEmblem).Y;

            imgEmblem.Cursor = Cursors.Hand;

        private void imgEmblem_MouseMove(object sender, MouseEventArgs e)
             if (_isLeftMouseDown == false)

              TranslateTransform tt = new TranslateTransform();

            if (_imgPosX != -1)
                tt.X = _imgPosX + (e.GetPosition(emblemDesign).X – _mousePosX);
            if (_imgPosY != -1)
                tt.Y = _imgPosY + (e.GetPosition(emblemDesign).Y – _mousePosY);
            imgEmblem.RenderTransform = tt;
            resizeCanvas.Margin = imgEmblem.Margin;
            System.Diagnostics.Debug.WriteLine(“X={0} y={1}”, tt.X, tt.Y);           

        private void imgEmblem_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            _isLeftMouseDown = false;
            imgEmblem.Cursor = Cursors.Arrow;

        private void emblemDesign_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
            //_isLeftMouseDown = false;


Written by Sony Arouje

August 25, 2010 at 4:22 pm

Posted in Silverlight

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: