可移动的自定义控件 [英] Moveable Custom Control

查看:90
本文介绍了可移动的自定义控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义控件,我希望用户能够拖动它。因此,我将以下代码放入自定义控件中:

I have a custom control and I want the user to be able to drag it. So I put in the following code in the custom control:

    void MoveableStackPanel_MouseMove(object sender, MouseEventArgs e)
    {
        if (IsMoving)
        {
            Point newLoc = e.GetPosition(null);
            MainWindow.Instance.Title = newLoc.ToString(); // Debug
            Margin = new Thickness(newLoc.X - 48, newLoc.Y - 48, 0, 0);
        }
    }

请注意代码中的 -48。
当鼠标向上或向左移动时,鼠标不再位于控件区域中,因此不再触发MouseMove事件。因此,我两次添加-48来解决此问题。但是当用户移动鼠标的速度快于框架可以更新的速度时,鼠标将移出控件区域,并且控件也将不再移动。

Note the "-48" in the code. When the mouse is moved up or left then the mouse is not in the controls area anymore and thus does no longer trigger the MouseMove event. So I added the -48 twice to work around that. But when the user moves the mouse faster than the framework can update then the mouse will get outside the controls area and the control also won't move anymore.

关于分配IMovableInterface并保留以主要形式移动的控件列表等,但这真是一件麻烦事,这样的解决方案是什么?

I was thinking about assigning an IMovableInterface and keep lists of controls that are moving in the main form and such but that is all such a hassle and such... What is the proper solution?

PS:控件是动态生成的,因此我需要使用C#代码而不是XML的解决方案。

P.S.: the controls are generated dynamically so I need the solution in C# code and not in XML.

推荐答案

尝试使用< a href = http://msdn.microsoft.com/zh-cn/library/system.windows.uielement.capturemouse.aspx rel = nofollow> CaptureMouse方法。

看看这样的事情是否对您有用。

See if something like this works for you.:

void moveableStackPanel1_MouseUp(object sender, MouseButtonEventArgs e)
    {
        ReleaseMouseCapture();
    }

    void moveableStackPanel1_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (IsEnabled && IsVisible)
            CaptureMouse();
    }

    void moveableStackPanel1_MouseMove(object sender, MouseEventArgs e)
    {
        if (IsMouseCaptured)
        {
            Point newLoc = e.GetPosition(null);
            Margin = new Thickness(newLoc.X, newLoc.Y, 0, 0);
        }
    } 

这篇关于可移动的自定义控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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