WPF使用GongSolutions.WPF.DragDrop进行不同数据类型拖拽

GongSolutions.WPF.DragDrop是一个很强大的WPF拖拽库github地址,我们看到Github上的ListBox拖拽例子是基于两个ListBox的ItemSorce的数据类型是相同的,如果两个ListBox上的ItemSource数据类型不一样,我们该怎么进行,这时就要使用这个dd:DragDrop.DropHandler这个属性进行后台的MVVM绑定。

1.正常设置这个几个属性

                 dd:DragDrop.IsDragSource="True" //是否开启拖拽源
                 dd:DragDrop.IsDropTarget="True" //是否是拖放目标
                 dd:DragDrop.DropTargetAdornerBrush="Red" //拖拽过程产生的效果

2.分别设置两个ListBox的DataTemplate数据展示模板,模板的数据是不同的类型ListDataLeftListDataRight

    <DataTemplate x:Key="LeftListBoxKey" DataType="{x:Type local:ListDataLeft}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Id}" Foreground="Green"/>
            <TextBlock  Margin="20,0,0,0" Text="{Binding Id}" FontSize="16" Foreground="Black"/>
            <TextBlock Margin="20,0,0,0" Text="{Binding Id}" Foreground="Gray"/>
        </StackPanel>
    </DataTemplate>

   <DataTemplate x:Key="RightListBoxKey" DataType="{x:Type local:ListDataRight}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Id}" Foreground="Green"/>
        <TextBlock  Margin="20,0,0,0" Text="{Binding Name}" FontSize="16" Foreground="Black"/>
        <TextBlock  Margin="20,0,0,0" Text="{Binding Description}"  Foreground="Red"/>
    </StackPanel>
</DataTemplate>
</Window.Resources>

 <Grid>
     <Grid.ColumnDefinitions>
         <ColumnDefinition Width="0.3*"/>
         <ColumnDefinition Width="*"/>
     </Grid.ColumnDefinitions>
     <ListBox x:Name="LeftListBox"
              Background="#1c1c1c"
              dd:DragDrop.IsDragSource="True"
              dd:DragDrop.IsDropTarget="False"
              dd:DragDrop.DropTargetAdornerBrush="Red"
              ItemTemplate="{StaticResource LeftListBoxKey}"
              ItemsSource="{Binding ListDataLefts}"
              >
     </ListBox>
 <!--其中dd:DragDrop.DropHandler="{Binding CopyDragHandler}" 是我们自定义拖放逻辑-->
     <ListBox x:Name="RightListBox"
              Background="Gray" Grid.Column="1"
              dd:DragDrop.IsDragSource="True"
              dd:DragDrop.IsDropTarget="True"
              dd:DragDrop.DropTargetAdornerBrush="Red"
              dd:DragDrop.DropHandler="{Binding CopyDragHandler}" 
              ItemTemplate="{StaticResource RightListBoxKey}"
              ItemsSource="{Binding listDataRights}"
              >
     </ListBox>
 </Grid>

3.创建其对应的ViewModel

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace DropDemo
{
    public class MainViewModel : INotifyPropertyChanged, IInsert
    {

        public ObservableCollection<ListDataLeft> ListDataLefts { get; set; }

        public ObservableCollection<ListDataRight> listDataRights { get; set; }


        public CopyDragHandler CopyDragHandler { get; set; }

        public void NotifyPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public MainViewModel()
        {
            CopyDragHandler = new CopyDragHandler(this);


            ListDataLefts = new ObservableCollection<ListDataLeft>()
            {
                new ListDataLeft()
                {
                    Id = 1,
                    Name="itemLeft1"
                },
                 new ListDataLeft()
                {
                    Id = 2,
                    Name="itemLeft2"
                },

                new ListDataLeft()
                {
                    Id = 3,
                    Name="itemLeft3"
                },

            };


            listDataRights = new ObservableCollection<ListDataRight>()
            {
                new ListDataRight() {
                    Id = 1,
                    Name="itemRight1",
                    Description="显示itemRight1"
                },
                new ListDataRight() {
                    Id = 2,
                    Name="itemRight2",
                    Description="显示itemRight2"
                },
                 new ListDataRight() {
                    Id = 3,
                    Name="itemRight3",
                    Description="显示itemRight3"
                }
            };
        }

        /// <summary>
        /// 插入元素
        /// </summary>
        /// <param name="index"></param>
        /// <param name="value"></param>
        public void Insert(int index, ListDataRight value, bool IsSameType = false)
        {
            int count=listDataRights.Count;
            if (!IsSameType)
            {
                if (count >= index)
                {
                    listDataRights.Insert(index, value);
                }
            }
            else
            {
                if (count > index)
                {
                    int oldIndex=listDataRights.IndexOf(value);
                    listDataRights.Move(oldIndex,index);
                }
                else if(count == index)
                {
                    listDataRights.Remove(value);
                    listDataRights.Add(value);
                }
            }

        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

    public class ListDataLeft
    {
        public int Id  { get; set; }

        public string Name { get; set; }


    }



    public class ListDataRight
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }

    }
}


4.实现CopyDragHandler,需要实现IDropTarget接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GongSolutions.Wpf.DragDrop;
namespace DropDemo
{
    public class CopyDragHandler : IDropTarget
    {

        private IInsert _insert;

        public CopyDragHandler(IInsert insert)
        {
            _insert = insert;
        }

        public void DragEnter(IDropInfo dropInfo)
        {
            
        }

        public void DragLeave(IDropInfo dropInfo)
        {
            
        }


        /// <summary>
        /// 悬浮在Item上执行操作
        /// </summary>
        /// <param name="dropInfo"></param>
        public void DragOver(IDropInfo dropInfo)
        {
            object sourceitem=dropInfo.Data;

            object targetitem=dropInfo.TargetItem;//拖拽到上方的子项

            if(sourceitem!=null && targetitem != null)
            {
                dropInfo.Effects = System.Windows.DragDropEffects.Copy;//显示可拖放
                dropInfo.DropTargetAdorner=DropTargetAdorners.Insert;
            }
        }

        public void Drop(IDropInfo dropInfo)
        {
            object sourceitem = dropInfo.Data;

            ListDataRight targetitem = dropInfo.TargetItem as ListDataRight;//拖拽到上方的子项

            int index = dropInfo.InsertIndex;//要插入到目标上的第几个位置

            if(sourceitem.GetType() == typeof(ListDataLeft))//如果是不同的数据类型
            {
                ListDataLeft listDataLeft = (ListDataLeft)sourceitem;
                ListDataRight listDataRight = new ListDataRight()
                {
                    Id = listDataLeft.Id,
                    Name = listDataLeft.Name,
                    Description = "itemRight"
                };
                _insert.Insert(index, listDataRight);
            }
            else if(sourceitem.GetType() == typeof(ListDataRight))//如果是相同的数据类型
            {
                ListDataRight listDataright = (ListDataRight)sourceitem;

                _insert.Insert(index, listDataright, true);
            }
        }
    }
}

最终效果实现了两个ListBox的ItemSource不同数据类型的拖拽操作
在这里插入图片描述

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 WPF DragDrop 例子: XAML 代码: ```xml <Window x:Class="WpfApp1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="450" Width="800"> <Grid> <StackPanel Orientation="Horizontal" Margin="10"> <TextBlock Text="Drag me:" Margin="0,0,10,0" /> <TextBlock Text="Hello, world!" Background="LightGray" Width="100" Height="50" PreviewMouseLeftButtonDown="TextBlock_PreviewMouseLeftButtonDown" PreviewMouseMove="TextBlock_PreviewMouseMove" PreviewMouseLeftButtonUp="TextBlock_PreviewMouseLeftButtonUp" /> </StackPanel> <StackPanel Orientation="Horizontal" Margin="10"> <TextBlock Text="Drop here:" Margin="0,0,10,0" /> <Border BorderBrush="Black" BorderThickness="1" Width="100" Height="50" AllowDrop="True" Drop="Border_Drop" /> </StackPanel> </Grid> </Window> ``` C# 代码: ```csharp using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace WpfApp1 { public partial class MainWindow : Window { private bool isDragging = false; private Point startPoint; public MainWindow() { InitializeComponent(); } private void TextBlock_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { startPoint = e.GetPosition(null); isDragging = true; } private void TextBlock_PreviewMouseMove(object sender, MouseEventArgs e) { if (isDragging && e.LeftButton == MouseButtonState.Pressed) { Point position = e.GetPosition(null); Vector offset = startPoint - position; if (Math.Abs(offset.X) > SystemParameters.MinimumHorizontalDragDistance || Math.Abs(offset.Y) > SystemParameters.MinimumVerticalDragDistance) { DataObject data = new DataObject("myFormat", "Hello, world!"); DragDrop.DoDragDrop((DependencyObject)sender, data, DragDropEffects.Copy); isDragging = false; } } } private void TextBlock_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { isDragging = false; } private void Border_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("myFormat")) { string text = (string)e.Data.GetData("myFormat"); ((Border)sender).Child = new TextBlock { Text = text, Background = Brushes.LightGray }; } } } } ``` 这个例子演示了如何在 WPF 中实现拖放操作。我们创建了一个包含两个 StackPanel 的 Window,第一个 StackPanel 包含一个 TextBlock,可以被拖动,第二个 StackPanel 包含一个 Border,可以接受拖放操作。当用户按下鼠标左键并移动 TextBlock 时,如果移动距离超过一定阈值,就会触发拖放操作。在拖放操作中,我们将一个字符串放入 DataObject 中,并指定数据格式为 "myFormat"。在 Border 的 Drop 事件中,我们检查数据格式是否为 "myFormat",如果是,就将字符串显示在 Border 中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值