简体   繁体   English

C#WPF-自定义控件拖放(Visual Studio样式)

[英]C# WPF - Custom Control drag and drop (Visual Studio style)

How do I make my Custom controls draggable and droppable on a grid let's say? 假设我如何使我的自定义控件在网格上可拖动和拖放?

I want to drag a panel(custom control) and drop it somewhere on my screen, in the best case in a grid, for example how it's done in Visual Studio, you can grab the solution explorer let's say and drop it somewhere, but how exactly do I do that? 我想将面板(自定义控件)拖放到屏幕上的某个位置,以网格中的最佳情况为例,例如在Visual Studio中是如何完成的,您可以抓住解决方案资源管理器,比如说将其拖放到某个位置,但是如何我到底要这么做吗?

I found this post with a very similar conclusion to this one. 我发现这篇文章的结论与此非常相似。 the difference being scale. 区别在于规模。

the following example will swap the parent container 以下示例将交换父容器

    int i = 0;
    void swapLocations()
    {

        foreach(var formObject in objList) //objList == a list or array on all objects you want to move from one container to another
        {

            if (i % 2 == 0)
            {

                // catch current position             
                Point moveLocation = new Point(formObject.Location.X + formObject.Parent.Location.X,formObject.Location.Y + formObject.Parent.Location.Y);

                // remove this object
                formObject.Parent.Controls.Remove(formObject);

                // add this object to the form
                this.Controls.Add(formObject);

                 // set location
                formObject.Location = moveLocation;

                formObject.SendToBack();
            }
            else
            {
                formObject.BringToFront();
            }
        }
        ++i;
    }

You need to build your project and then it will be automatically available in the Toolbox when you are in the XAML designer. 您需要构建项目,然后当您在XAML设计器中时,它将在工具箱中自动可用。 Just like the common controls. 就像常用控件一样。

For Drag and Drop at runtime look and the official WPF documentation . 有关在运行时进行拖放的信息,请查看WPF官方文档 Also I suggest you look at the GongSolutions.WPF.DragDrop library in GitHub it is open source so you can see how they implemented it if the functionality it provides does not do what you want. 我还建议您查看GitHub中的GongSolutions.WPF.DragDrop库,它是开源的,因此,如果它提供的功能无法满足您的要求,您可以了解他们如何实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM