1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// XAML

<Window x:Class="MyProject.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="500" Width="500">
    <Grid>
        <Canvas x:Name="mycanv">
            <Image Width="150" x:Name="myimg" Source="some_source.png"/>
        </Canvas>
    </Grid>
</Window>

//C#

private Point mouseClick;
private double canvasLeft;
private double canvasTop;
public Window1()
{
    InitializeComponent();
    foreach (object obj in mycanv.Children)
    {
        try
        {
            Image img = (Image)obj;
            img.PreviewMouseDown += new MouseButtonEventHandler(myimg_MouseDown);
            img.PreviewMouseMove += new MouseEventHandler(myimg_MouseMove);
            img.PreviewMouseUp += new MouseButtonEventHandler(myimg_MouseUp);
            img.TextInput += new TextCompositionEventHandler(myimg_TextInput);
            img.LostMouseCapture += new MouseEventHandler(myimg_LostMouseCapture);
            img.SetValue(Canvas.LeftProperty, 0.0);
            img.SetValue(Canvas.TopProperty, 0.0);
        }
        catch
        {
            //do something
        }
    }
}

void myimg_LostMouseCapture(object sender, MouseEventArgs e)
{
    ((Image)sender).ReleaseMouseCapture();
}

void myimg_TextInput(object sender, TextCompositionEventArgs e)
{
    ((Image)sender).ReleaseMouseCapture();
}

void myimg_MouseUp(object sender, MouseButtonEventArgs e)
{
    ((Image)sender).ReleaseMouseCapture();
}

void myimg_MouseMove(object sender, MouseEventArgs e)
{
    if (((Image)sender).IsMouseCaptured)
    {
        Point mouseCurrent = e.GetPosition(null);
        double Left = mouseCurrent.X - canvasLeft;
        double Top = mouseCurrent.Y - canvasTop;
        ((Image)sender).SetValue(Canvas.LeftProperty, canvasLeft + Left);
        ((Image)sender).SetValue(Canvas.TopProperty, canvasTop + Top);
        canvasLeft = Canvas.GetLeft(((Image)sender));
        canvasTop = Canvas.GetTop(((Image)sender));
    }
}

void myimg_MouseDown(object sender, MouseButtonEventArgs e)
{
    mouseClick = e.GetPosition(null);
    canvasLeft = Canvas.GetLeft(((Image)sender));
    canvasTop = Canvas.GetTop(((Image)sender));
    ((Image)sender).CaptureMouse();
}