当前位置:网站首页>【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的位置坐标!
效果展示

边栏推荐
猜你喜欢

GBJ1510-ASEMI机器人电源整流桥GBJ1510

GB28181 sip和RTSP(Real-Time Streaming Protocol)实时流控制协议

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

Research on Ethernet PHY Chip LAN8720A Chip

惊掉你下巴,程序员编码竟然可以被 996 指数化

Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate
Fedora 36 dnf 安装ModSecurity和 OWASP 核心规则集

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

以太网PHY芯片LAN8720A芯片研究

卷积神经网络识别验证码
随机推荐
Unity image使用长图后 图片很糊
eyb:Redis学习(4)
将string类对象中的内容格式化到字符串Buffer中时遇到的异常崩溃分析
破产企业的职工退休怎么办?
C language structure, function and pointer exercise (simple address book)
What should I do if there is no sound after reinstalling the system in win10?
R语言使用coxph函数构建生存分析回归模型,使用forestmodel包的forest_model函数可视化生存回归模型对应的森林图
CAS:183896-00-6 (Biotin-PEG3-C3-NH2) PEG derivative
hint: Updates were rejected because the tip of your current branch is behind hint: its remote counte
Visual low-code system practice based on design draft identification
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
R语言使用glm函数构建logistic回归模型,使用forestmodel包的forest_model函数可视化逻辑回归模型对应的森林图
删除表空间数据文件
数据建模已死,真的吗?
3511. 倒水问题
Entity FrameWork Core教程,从基础应用到原理实战
Prometeus 2.31.0 新特性
ITK编译remote库
SonarQube升级记录:7.8->7.9->8.9
Not, even the volume of the king to write code in the company are copying and pasting it reasonable?