在WPF中的两个数据网格之间拖放(C#)

在WPF中的两个数据网格之间拖放(C#),c#,wpf,datagrid,drag-and-drop,C#,Wpf,Datagrid,Drag And Drop,对不起,我的英语不是我的母语。如果你不明白什么,请告诉我 我正在启动C#和WPF,我需要在两个datagrid之间实现拖放功能。我已经搜索了很多,但没有找到任何对我有帮助的东西。它总是显示如何在两个不同的控件之间进行拖放,或者只在同一个datagrid中进行拖放,而我无法根据自己的需要调整这些答案,因为我不了解解决方案的某些部分。 所以我来这里是想问一个非常精确的问题:如何在两个数据网格之间实现拖放 如果您能帮助我,我将非常感激。这是一个示例代码() 定义MouseDown事件 定义MouseM

对不起,我的英语不是我的母语。如果你不明白什么,请告诉我

我正在启动C#和WPF,我需要在两个datagrid之间实现拖放功能。我已经搜索了很多,但没有找到任何对我有帮助的东西。它总是显示如何在两个不同的控件之间进行拖放,或者只在同一个datagrid中进行拖放,而我无法根据自己的需要调整这些答案,因为我不了解解决方案的某些部分。 所以我来这里是想问一个非常精确的问题:如何在两个数据网格之间实现拖放

如果您能帮助我,我将非常感激。

这是一个示例代码()

  • 定义MouseDown事件
  • 定义MouseMove事件以启动DragAndDrop操作
  • 定义DragOver以测试是否允许跌落
  • 定义Drop事件以执行Drop操作
  • 您可以对两个datagrid使用相同的事件

        private Point? _startPoint;
    
        private void dataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            _startPoint = e.GetPosition(null);
        }
    
        private void dataGrid_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            // No drag operation
            if (_startPoint == null)
                return;
    
            var dg = sender as DataGrid;
            if (dg == null) return; 
            // Get the current mouse position
            Point mousePos = e.GetPosition(null);
            Vector diff = _startPoint.Value - mousePos;
            // test for the minimum displacement to begin the drag
            if (e.LeftButton == MouseButtonState.Pressed &&
                (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
                Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
            {
    
                // Get the dragged DataGridRow
                var DataGridRow=
                    FindAnchestor<DataGridRow>((DependencyObject)e.OriginalSource);
    
                if (DataGridRow == null)
                    return;
                // Find the data behind the DataGridRow
                var dataTodrop = (DataModel)dg.ItemContainerGenerator.
                    ItemFromContainer(DataGridRow);
    
                if (dataTodrop == null) return;
    
                // Initialize the drag & drop operation
                var dataObj = new DataObject(dataTodrop);
                dataObj.SetData("DragSource", sender);
                DragDrop.DoDragDrop(dg, dataObj, DragDropEffects.Copy);
                _startPoint = null;
            }
        }
    
        private void dataGrid_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            _startPoint = null;
        }
    
        private void dataGrid_Drop(object sender, DragEventArgs e)
        {
            var dg = sender as DataGrid;
            if (dg == null) return;
            var dgSrc = e.Data.GetData("DragSource") as DataGrid;
            var data = e.Data.GetData(typeof(DataModel));
            if (dgSrc == null || data == null) return;
            // Implement move data here, depends on your implementation
            MoveDataFromSrcToDest(dgSrc, dg, data);
            // OR
            MoveDataFromSrcToDest(dgSrc.DataContext, dg.DataContext, data);
        }
    
        private void dataGrid_PreviewDragOver(object sender, DragEventArgs e)
        {
             // TO test if drop is allowed, to avoid drop 
             // if false e.Effects = DragDropEffects.None;
        }
    
    
        // Helper to search up the VisualTree
        private static T FindAnchestor<T>(DependencyObject current)
            where T : DependencyObject
        {
            do
            {
                if (current is T)
                {
                    return (T)current;
                }
                current = VisualTreeHelper.GetParent(current);
            }
            while (current != null);
            return null;
        }
    
    私人点_起点;
    私有void dataGrid_PreviewMouseLeftButtonDown(对象发送器,鼠标按钮ventargs e)
    {
    _startPoint=e.GetPosition(null);
    }
    私有void dataGrid_PreviewMouseMove(对象发送器,MouseEventArgs e)
    {
    //无拖动操作
    如果(_startPoint==null)
    返回;
    var dg=发送方作为数据网格;
    如果(dg==null)返回;
    //获取当前鼠标位置
    鼠标点=e.GetPosition(null);
    向量差=_startPoint.Value-鼠标点;
    //测试开始拖动的最小位移
    如果(e.LeftButton==鼠标按钮状态。按下&&
    (数学Abs(diff.X)>系统参数。最小水平牵引距离||
    数学。Abs(差异Y)>系统参数。最小垂直牵引距离)
    {
    //获取拖动的DataGridRow
    var数据网格行=
    findanchester((DependencyObject)e.OriginalSource);
    if(DataGridRow==null)
    返回;
    //查找DataGridRow后面的数据
    var dataTodrop=(数据模型)dg.ItemContainerGenerator。
    ItemFromContainer(DataGridRow);
    if(dataTodrop==null)返回;
    //初始化拖放操作
    var dataObj=新的数据对象(dataTodrop);
    dataObj.SetData(“DragSource”,发送方);
    DragDrop.DoDragDrop(dg、dataObj、DragDropEffects.Copy);
    _startPoint=null;
    }
    }
    私有void dataGrid_PreviewMouseUp(对象发送器,鼠标按钮ventargs e)
    {
    _startPoint=null;
    }
    私有void dataGrid_Drop(对象发送方,DragEventArgs e)
    {
    var dg=发送方作为数据网格;
    如果(dg==null)返回;
    var dgSrc=e.Data.GetData(“DragSource”)作为DataGrid;
    var data=e.data.GetData(typeof(DataModel));
    if(dgSrc==null | | data==null)返回;
    //在此处实现移动数据,具体取决于您的实现
    MoveDataFromSrcToDest(dgSrc,dg,数据);
    //或
    MoveDataFromSrcToDest(dgSrc.DataContext,dg.DataContext,data);
    }
    私有void dataGrid_PreviewDragOver(对象发送方,DragEventArgs e)
    {
    //测试是否允许跌落,避免跌落
    //如果为假,e.Effects=DragDropEffects.None;
    }
    //帮助搜索VisualTree
    专用静态T Findanchester(DependencyObject当前)
    其中T:DependencyObject
    {
    做
    {
    如果(电流为T)
    {
    返回(T)电流;
    }
    当前=VisualTreeHelper.GetParent(当前);
    }
    while(当前!=null);
    返回null;
    }
    

    希望得到以下帮助:)

    为此,您需要两个Datagrid提要列表或类似于xaml中的observableCollection:

    <DataGrid AllowDrop="True" Name="dg1" Margin="10,50,10,30" Grid.Column="1">
        //Set your column and what you want
    </DataGrid>
    <DataGrid Name="dg2" AllowDrop="True" Margin="10,50,10,30" Grid.Column="2">
        //Set your column and what you want
    </DataGrid>
    
    然后将所有这些添加到主窗口之后:

    void Dg_Drop(object sender, DragEventArgs e)
            {
                int index = -1;
                DataGrid dg = new DataGrid();
                if (sender is DataGrid)
                {
                    dg = (DataGrid)sender;
                }
                if (rowIndex < 0)
                    return;
                if (dg.Name == "dg1")
                {
                    index = this.GetCurrentRowIndexSupp(e.GetPosition);
                }
                if (dg.Name == "dg2")
                {
                    index = this.GetCurrentRowIndexAdd(e.GetPosition);
                }
                if (index < 0)
                    return;
                if (index == rowIndex)
                    return;
                if (index == dg.Items.Count - 1)
                {
                    MessageBox.Show("Last line can't moove");
                    return;
                }
                if (dg.Name == "dg1")
                {
                    if (dgName == "dg2")
                    {
                        DataOfGrid changedProduct = yourlist2[rowIndex];
                        yourlist2.RemoveAt(rowIndex);
                        yourlist1.Insert(index, changedProduct);
                    }
                    else
                    {
                        DataOfGrid changedProduct = yourlist1[rowIndex];
                        yourlist1.RemoveAt(rowIndex);
                        yourlist1.Insert(index, changedProduct);
                    }
                }
                if (dg.Name == "dg2")
                {
                    if (dgName == "dg1")
                    {
                        DataOfGrid changedProduct = yourlist1[rowIndex];
                        yourlist1.RemoveAt(rowIndex);
                        yourlist2.Insert(index, changedProduct);
                    }
                    else
                    {
                        DataOfGrid changedProduct = yourlist2[rowIndex];
                        yourlist2.RemoveAt(rowIndex);
                        yourlist2.Insert(index, changedProduct);
                    }
                }
                dg1.ItemsSource = yourlist1;
                dg1.Items.Refresh();
                dg2.ItemsSource = yourlist2;
                dg2.Items.Refresh();
            }
    
            void DgSupp_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                DataGrid dg = new DataGrid();
                if (sender is DataGrid)
                {
                    dg = (DataGrid)sender;
                }
                if (dg.Name == "dg1")
                {
                    rowIndex = GetCurrentRowIndexSupp(e.GetPosition);
                    dgName = dg.Name;
                }
                if (dg.Name == "dg2")
                {
                    rowIndex = GetCurrentRowIndexAdd(e.GetPosition);
                    dgName = dg.Name;
                }
                if (rowIndex < 0)
                    return;
                dg.SelectedIndex = rowIndex;
                DataOfGrid selectedEmp = dg.Items[rowIndex] as DataOfGrid;
                if (selectedEmp == null)
                    return;
                DragDropEffects dragdropeffects = DragDropEffects.Move;
                if (DragDrop.DoDragDrop(dg, selectedEmp, dragdropeffects)
                                    != DragDropEffects.None)
                {
                    dg.SelectedItem = selectedEmp;
                }
            }
    
            private bool GetMouseTargetRow(Visual theTarget, GetPosition position)
            {
                Rect rect = VisualTreeHelper.GetDescendantBounds(theTarget);
                Point point = position((IInputElement)theTarget);
                return rect.Contains(point);
            }
    
            private DataGridRow GetRowItemList1(int index)
            {
                if (dg1.ItemContainerGenerator.Status
                        != GeneratorStatus.ContainersGenerated)
                    return null;
                return dg1.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
            }
    
            private DataGridRow GetRowItemList2(int index)
            {
                if (dg2.ItemContainerGenerator.Status
                        != GeneratorStatus.ContainersGenerated)
                    return null;
                return dg2.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
            }
    
            private int GetCurrentRowIndexSupp(GetPosition pos)
            {
                int curIndex = -1;
                for (int i = 0; i < dg1.Items.Count; i++)
                {
                    DataGridRow itm = GetRowItemList1(i);
                    if (GetMouseTargetRow(itm, pos))
                    {
                        curIndex = i;
                        break;
                    }
                }
                return curIndex;
            }
    
            private int GetCurrentRowIndexAdd(GetPosition pos)
            {
                int curIndex = -1;
                for (int i = 0; i < dg2.Items.Count; i++)
                {
                    DataGridRow itm = GetRowItemList2(i);
                    if (GetMouseTargetRow(itm, pos))
                    {
                        curIndex = i;
                        break;
                    }
                }
                return curIndex;
            }
    
    void Dg_Drop(对象发送器,DragEventArgs e)
    {
    int指数=-1;
    DataGrid dg=新DataGrid();
    如果(发送方是DataGrid)
    {
    dg=(数据网格)发送方;
    }
    如果(行索引<0)
    返回;
    如果(dg.Name==“dg1”)
    {
    index=this.GetCurrentRowIndexSupp(e.GetPosition);
    }
    如果(dg.Name==“dg2”)
    {
    索引=此.GetCurrentRowIndexAdd(e.GetPosition);
    }
    如果(指数<0)
    返回;
    如果(索引==行索引)
    返回;
    如果(索引==dg.Items.Count-1)
    {
    Show(“最后一行不能移动”);
    返回;
    }
    如果(dg.Name==“dg1”)
    {
    如果(dgName==“dg2”)
    {
    DataOfGrid changedProduct=yourlist2[rowIndex];
    yourlist2.RemoveAt(行索引);
    您的列表1.插入(索引,更改产品);
    }
    其他的
    {
    DataOfGrid changedProduct=yourlist1[rowIndex];
    yourlist1.RemoveAt(行索引);
    您的列表1.插入(索引,更改产品);
    }
    }
    如果(dg.Name==“dg2”)
    {
    如果(dgName==“dg1”)
    {
    DataOfGrid changedProduct=yourlist1[rowIndex];
    yourlist1.RemoveAt(行索引);
    您的列表2.插入(索引,更改产品);
    }
    其他的
    {
    DataOfGrid changedProduct=yourlist2[rowIndex];
    yourlist2.RemoveAt(行索引);
    您的列表2.插入(索引,更改产品);
    }
    }
    dg1.ItemsSource=yourlist1;
    dg1.Items.Refresh();
    dg2.ItemsSource=yourlist2;
    dg2.Items.Refresh();
    }
    无效DGSUPPP
    
    void Dg_Drop(object sender, DragEventArgs e)
            {
                int index = -1;
                DataGrid dg = new DataGrid();
                if (sender is DataGrid)
                {
                    dg = (DataGrid)sender;
                }
                if (rowIndex < 0)
                    return;
                if (dg.Name == "dg1")
                {
                    index = this.GetCurrentRowIndexSupp(e.GetPosition);
                }
                if (dg.Name == "dg2")
                {
                    index = this.GetCurrentRowIndexAdd(e.GetPosition);
                }
                if (index < 0)
                    return;
                if (index == rowIndex)
                    return;
                if (index == dg.Items.Count - 1)
                {
                    MessageBox.Show("Last line can't moove");
                    return;
                }
                if (dg.Name == "dg1")
                {
                    if (dgName == "dg2")
                    {
                        DataOfGrid changedProduct = yourlist2[rowIndex];
                        yourlist2.RemoveAt(rowIndex);
                        yourlist1.Insert(index, changedProduct);
                    }
                    else
                    {
                        DataOfGrid changedProduct = yourlist1[rowIndex];
                        yourlist1.RemoveAt(rowIndex);
                        yourlist1.Insert(index, changedProduct);
                    }
                }
                if (dg.Name == "dg2")
                {
                    if (dgName == "dg1")
                    {
                        DataOfGrid changedProduct = yourlist1[rowIndex];
                        yourlist1.RemoveAt(rowIndex);
                        yourlist2.Insert(index, changedProduct);
                    }
                    else
                    {
                        DataOfGrid changedProduct = yourlist2[rowIndex];
                        yourlist2.RemoveAt(rowIndex);
                        yourlist2.Insert(index, changedProduct);
                    }
                }
                dg1.ItemsSource = yourlist1;
                dg1.Items.Refresh();
                dg2.ItemsSource = yourlist2;
                dg2.Items.Refresh();
            }
    
            void DgSupp_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                DataGrid dg = new DataGrid();
                if (sender is DataGrid)
                {
                    dg = (DataGrid)sender;
                }
                if (dg.Name == "dg1")
                {
                    rowIndex = GetCurrentRowIndexSupp(e.GetPosition);
                    dgName = dg.Name;
                }
                if (dg.Name == "dg2")
                {
                    rowIndex = GetCurrentRowIndexAdd(e.GetPosition);
                    dgName = dg.Name;
                }
                if (rowIndex < 0)
                    return;
                dg.SelectedIndex = rowIndex;
                DataOfGrid selectedEmp = dg.Items[rowIndex] as DataOfGrid;
                if (selectedEmp == null)
                    return;
                DragDropEffects dragdropeffects = DragDropEffects.Move;
                if (DragDrop.DoDragDrop(dg, selectedEmp, dragdropeffects)
                                    != DragDropEffects.None)
                {
                    dg.SelectedItem = selectedEmp;
                }
            }
    
            private bool GetMouseTargetRow(Visual theTarget, GetPosition position)
            {
                Rect rect = VisualTreeHelper.GetDescendantBounds(theTarget);
                Point point = position((IInputElement)theTarget);
                return rect.Contains(point);
            }
    
            private DataGridRow GetRowItemList1(int index)
            {
                if (dg1.ItemContainerGenerator.Status
                        != GeneratorStatus.ContainersGenerated)
                    return null;
                return dg1.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
            }
    
            private DataGridRow GetRowItemList2(int index)
            {
                if (dg2.ItemContainerGenerator.Status
                        != GeneratorStatus.ContainersGenerated)
                    return null;
                return dg2.ItemContainerGenerator.ContainerFromIndex(index) as DataGridRow;
            }
    
            private int GetCurrentRowIndexSupp(GetPosition pos)
            {
                int curIndex = -1;
                for (int i = 0; i < dg1.Items.Count; i++)
                {
                    DataGridRow itm = GetRowItemList1(i);
                    if (GetMouseTargetRow(itm, pos))
                    {
                        curIndex = i;
                        break;
                    }
                }
                return curIndex;
            }
    
            private int GetCurrentRowIndexAdd(GetPosition pos)
            {
                int curIndex = -1;
                for (int i = 0; i < dg2.Items.Count; i++)
                {
                    DataGridRow itm = GetRowItemList2(i);
                    if (GetMouseTargetRow(itm, pos))
                    {
                        curIndex = i;
                        break;
                    }
                }
                return curIndex;
            }