Click here to Skip to main content
15,915,786 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,
i have created a dragabke Usercontrol. It should be Possible to drag it around in a Canvas. On the User Control i have implemented the logic for Drag and drop using three Mouse Events:

bool isMouseCaptured;
double mouseVerticalPosition;
double mouseHorizontalPosition;
C#
public void Handle_MouseDown (object sender, MouseEventArgs args) 
{
    Rectangle item = sender as Rectangle;
    mouseVerticalPosition = args.GetPosition(null).Y;
    mouseHorizontalPosition = args.GetPosition(null).X;
    isMouseCaptured = true;
    item.CaptureMouse();
}

public void Handle_MouseMove(object sender, MouseEventArgs args) 
{
    Rectangle item = sender as Rectangle;
    if (isMouseCaptured) 
    {

        // Calculate the current position of the object.
        double deltaV = args.GetPosition(null).Y - mouseVerticalPosition;
        double deltaH = args.GetPosition(null).X - mouseHorizontalPosition;
        double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
        double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);

        // Set new position of object.
        item.SetValue(Canvas.TopProperty, newTop);
        item.SetValue(Canvas.LeftProperty, newLeft);

        // Update position global variables.
        mouseVerticalPosition = args.GetPosition(null).Y;
        mouseHorizontalPosition = args.GetPosition(null).X;
    }
}

public void Handle_MouseUp(object sender, MouseEventArgs args) 
{
    Rectangle item = sender as Rectangle;
    isMouseCaptured = false;
    item.ReleaseMouseCapture();
    mouseVerticalPosition = -1;
    mouseHorizontalPosition = -1;
}


If i add the User Control form VS Toolbox to my Project, everything works fine, but
if i add the control During Runtime with:
C#
myControl ctrl = new myControl();
myCanvas.Children.Add(ctrl);


Dragging does not work. I can`t understand it.
Any suggestions what is wrong, or what to do?

greets
Posted

1 solution

My very first thought is that you may have forgotten to subscribe the event handlers to the events on the new control.
 
Share this answer
 
Comments
Motil88 2-Apr-12 1:43am    
Of course i subscribed the Eventhandlers, because if i put the dragdrop logic under comment, and use a MessageBox.Show(); the Message Box appears! This is the thing why i can`t understand it. :(

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900