在运行时添加控件时,USercontrol的拖动不起作用 [英] Dragging of USercontrol does not Work when Control Added while runtime

查看:76
本文介绍了在运行时添加控件时,USercontrol的拖动不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,
我创建了一个Dragabke用户控件.应该可以在画布中拖动它.在用户控件上,我使用三个鼠标事件实现了拖放的逻辑:

bool isMouseCaptured;
double mouseVerticalPosition;
double mouseHorizo​​ntalPosition;

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;

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;
}



如果我将VS工具箱添加到用户控制窗体中,则一切正常,但是
如果我在运行时添加以下控件:



If i add the User Control form VS Toolbox to my Project, everything works fine, but
if i add the control During Runtime with:

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

推荐答案

我的第一个想法是,您可能忘记了将事件处理程序订阅到新控件上的事件.
My very first thought is that you may have forgotten to subscribe the event handlers to the events on the new control.


这篇关于在运行时添加控件时,USercontrol的拖动不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆