WPF实现拖动控件功能(类似从工具箱拖出工具)

一、背景

下面代码只是简单示例,未使用MVVM模式编写

二、工具箱(ListBox)

2.1 前端代码

复制代码
<!-- 工具箱 -->
<ListBox Grid.Column="0" x:Name="Toolbox">
    <ListBoxItem>Tool 1</ListBoxItem>
    <ListBoxItem>Tool 2</ListBoxItem>
    <!-- 添加更多工具 -->
</ListBox>

2.2 前端事件

复制代码
<Window.Resources>
    <Style TargetType="ListBoxItem">
        <EventSetter Event="PreviewMouseMove" Handler="ListBoxItem_PreviewMouseMove"/>
    </Style>
</Window.Resources>

2.2 后端拖动代码

cs 复制代码
private void ListBoxItem_PreviewMouseMove(object sender, MouseEventArgs e)
{
    if(sender is ListBoxItem item)
    {
        DragDrop.DoDragDrop(item, item.Content, DragDropEffects.Copy);
    }        
}

三、工作页面(Canvas)

3.1 前端代码

cs 复制代码
<!-- 流程图容器 -->
<Canvas Grid.Column="1" x:Name="FlowChartCanvas" Background="White" AllowDrop="True" PreviewDragOver="FlowChartCanvas_PreviewDragOver" PreviewDrop="FlowChartCanvas_PreviewDrop">
    <!-- 流程图元素 -->
</Canvas>

3.2 后端获取工具放置坐标

cs 复制代码
private Point startPoint;


private void FlowChartCanvas_PreviewDragOver(object sender, DragEventArgs e)
{
        startPoint = e.GetPosition(FlowChartCanvas);        
}

3.3 后端放置工具

cs 复制代码
private void FlowChartCanvas_PreviewDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.StringFormat))
    {
        var tool = e.Data.GetData(DataFormats.StringFormat) as string;
        if (tool != null)
        {
            var element = new TextBlock
            {
                Text = tool,
                Background = Brushes.LightBlue,
                Width = 100,
                Height = 30
            };
            Canvas.SetLeft(element, startPoint.X);
            Canvas.SetTop(element, startPoint.Y);
            FlowChartCanvas.Children.Add(element);
        }
    }
}
相关推荐
武藤一雄3 分钟前
[奇淫巧技] WPF篇 (长期更新)
windows·microsoft·c#·.net·wpf
Psycho_MrZhang2 小时前
Airflow简介和架构
架构·wpf
没有bug.的程序员5 小时前
微服务中的数据一致性困局
java·jvm·微服务·架构·wpf·电商
Aevget6 小时前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(二)?
wpf·devexpress·.net 10·data grid
没有bug.的程序员2 天前
SOA、微服务、分布式系统的区别与联系
java·jvm·微服务·架构·wpf·日志·gc
Macbethad2 天前
基于WPF的半导体设备配方管理程序技术方案
wpf
FuckPatience2 天前
WPF Geometry
wpf
武藤一雄3 天前
.NET 中常见计时器大全
microsoft·微软·c#·.net·wpf·.netcore
MarkHD3 天前
车辆TBOX科普 第70次 AUTOSAR Adaptive、容器化与云原生的融合革命
云原生·wpf
极客智造3 天前
WPF Behavior 实战:自定义 InvokeCommandAction 实现事件与命令解耦
wpf