WPF Item拖拽 DragDrop

今天有个需求是需要拖拽DataGrid中的item到另一个DataGrid。自己实现还比较繁琐,网上查了查,发现一个不错的开源项目

gong-wpf-dragdrop

nuget安装下:Install-Package gong-wpf-dragdrop -Version 1.1.0

在xaml中添加引用: xmlns:dd="clr-namespace:GongSolutions.Wpf.DragDrop;assembly=GongSolutions.Wpf.DragDrop"

然后在datagrid中添加附加属性

<Window x:Class="WpfApp8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp8"
        xmlns:dd="clr-namespace:GongSolutions.Wpf.DragDrop;assembly=GongSolutions.Wpf.DragDrop"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <DataGrid x:Name="grid1" dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True" HorizontalAlignment="Left" Height="344" Margin="42,37,0,0" VerticalAlignment="Top" Width="292"/>


        <DataGrid x:Name="grid2"  dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True"  HorizontalAlignment="Left" Height="344" Margin="415,37,0,0" VerticalAlignment="Top" Width="321"/>
        
    </Grid>
</Window>

dd:DragDrop.IsDragSource="True" dd:DragDrop.IsDropTarget="True"

后台绑定下数据源

注:如果grid2的数据源item类型与grid1不一致,是不可以拖拽的。

可以支持多行拖拽。

原文地址:https://www.cnblogs.com/czly/p/10470759.html