当前位置:网站首页>【wpf】拖拽的简单实现
【wpf】拖拽的简单实现
2022-08-10 00:54:00 【code bean】
前台代码部分
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Background="AliceBlue">
<Border Height="40" Background="Chocolate" MouseLeftButtonDown="Border_MouseLeftButtonDown">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">拖拽</TextBlock>
</Border>
</StackPanel>
<Canvas x:Name="canvas" Grid.Column="1" Drop="Canvas_Drop" AllowDrop="True" Background="Transparent"/>
</Grid>
这里有个几个注意的地方:
1 cavar是拖拽的放置对象,需要设置如下:
- Drop事件,拖拽完成时触发
- AllowDrop, 允许拖拽
- Background,设置一个颜色,不然无法接收到事件。
三者缺一不可。
后台代码部分
Border 是被拖拽的对象,在鼠标左键按下后,需要在后台添加一些代码。
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Border border = (Border)sender;
DragDrop.DoDragDrop(border, "test", DragDropEffects.Copy);
}
这是一个创建拖拽对象的过程。 后续可以在拖拽事件中获取相应的参数:
private void Canvas_Drop(object sender, DragEventArgs e)
{
var data = e.Data.GetData(typeof(string));
Button btn = new Button();
btn.Content = data;
canvas.Children.Add(btn);
var point = e.GetPosition(canvas);
Canvas.SetLeft(btn, point.X);
Canvas.SetTop(btn, point.Y);
Debug.WriteLine("Canvas_Drop");
}
e.Data.GetData(typeof(string)); 获取的是我创建拖拽对象时,传入的第二个参数。
e.GetPosition(canvas); 可以获取拖拽完成时,鼠标相对于canvas的位置坐标!
效果展示

边栏推荐
猜你喜欢

ITK编译remote库

万字总结:分布式系统的38个知识点

高校就业管理系统设计与实现

PEG derivative Biotin-PEG1-OH (cas: 95611-10-2, 2-biotinaminoethanol) advantage description

y92.第六章 微服务、服务网格及Envoy实战 -- Envoy基础(三)

Docker interview question 2--get the number of database connections and docker-compose

Solidity最强对手:MOVE语言及新公链崛起

What should I do if there is no sound after reinstalling the system in win10?

ABAP 里文件操作涉及到中文字符集的问题和解决方案

Solidity最强对手:MOVE语言及新公链崛起
随机推荐
Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate
Minimum number of steps to get out of the maze 2
多线程之享元模式和final原理
UI遍历的初步尝试
[Turn] Typora_Markdown_ picture title (caption)
Teach you how to write performance test cases
2022金九银十工作潮,怎么样才能成功跳槽面试拿到高薪呢?
CMake 编译运行dpdk项目程序
03|Process Control
【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price
y92.第六章 微服务、服务网格及Envoy实战 -- Envoy基础(三)
Visual low-code system practice based on design draft identification
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
【报错】ModuleNotFoundError: No module named ‘scp‘
MySQL最大连接数限制如何修改
破产企业的职工退休怎么办?
RedHat红帽RHEL7安装与使用,VMware Workstation16 Pro虚拟机的安装与使用
什么是 PWA
彩色袜子题
Unity顶点动画