Виталий Asked:2020-05-05 14:57:49 +0800 CST2020-05-05 14:57:49 +0800 CST 2020-05-05 14:57:49 +0800 CST 移动表单元素 772 来自“帮助谷歌”系列的问题。 有一个面板,其中有几个元素(比如说按钮)在宽度上被拉伸并从上到下跟随。 我需要添加将一个元素拖放到另一个元素的能力,而且,当用户持有该元素时,其他元素必须提前移动。简而言之,逻辑就像手机桌面上的图标。 我不知道如何用谷歌搜索这样的指南。 知道元素在列表中的位置也非常重要。 它是在 WinForms 还是 WPF 上都没关系。 c# 2 个回答 Voted Best Answer Alexander Petrov 2020-05-05T21:43:11+08:002020-05-05T21:43:11+08:00 Windows 窗体上的完整示例。 using System.Drawing; using System.Windows.Forms; namespace WinFormApp1 { public partial class Form1 : Form { TableLayoutPanel tableLayoutPanel; public Form1() { //InitializeComponent(); Width = 500; tableLayoutPanel = new TableLayoutPanel { Parent = this, Dock = DockStyle.Top, AllowDrop = true, ColumnCount = 5, Height = 200 }; for (int i = 0; i < 15; i++) { var button = new Button { Parent = tableLayoutPanel, Text = "Button" + i }; button.MouseDown += Button_MouseDown; button.MouseMove += Button_MouseMove; button.MouseUp += Button_MouseUp; button.MouseClick += Button_MouseClick; } tableLayoutPanel.DragOver += TableLayoutPanel_DragOver; } private void Button_MouseDown(object sender, MouseEventArgs e) { ((Button)sender).Tag = new object(); } private void Button_MouseMove(object sender, MouseEventArgs e) { var button = (Button)sender; if (button.Tag != null) button.DoDragDrop(sender, DragDropEffects.Move); } private void Button_MouseUp(object sender, MouseEventArgs e) { ((Button)sender).Tag = null; } private void Button_MouseClick(object sender, MouseEventArgs e) { Text = ((Control)sender).Text; } private void TableLayoutPanel_DragOver(object sender, DragEventArgs e) { if (!e.Data.GetDataPresent(typeof(Button))) return; e.Effect = e.AllowedEffect; var draggedButton = (Button)e.Data.GetData(typeof(Button)); var pt = tableLayoutPanel.PointToClient(new Point(e.X, e.Y)); var button = (Button)tableLayoutPanel.GetChildAtPoint(pt); if (button != null) { var pos = tableLayoutPanel.GetPositionFromControl(button); tableLayoutPanel.Controls.Add(draggedButton, pos.Column, pos.Row); draggedButton.Tag = null; } } } } Digital Core 2020-05-05T15:44:01+08:002020-05-05T15:44:01+08:00 此处描述了实现:https ://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/walkthrough-enabling-drag-and-drop-on-a-user-control
Windows 窗体上的完整示例。
此处描述了实现:https ://docs.microsoft.com/en-us/dotnet/framework/wpf/advanced/walkthrough-enabling-drag-and-drop-on-a-user-control