本文主要是介绍wpf DataGrid 实现拖拽变换位置,双击拖拽向下自动滚动,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
- DataGrid_Drop事件是在拖放操作中释放拖动的对象时触发的事件。
- 使用VisualTreeHelper.HitTest方法获取鼠标释放位置的目标元素。
循环向上遍历VisualTree,直到找到DataGridRow为止。
如果找到DataGridRow,则获取其索引。
检查索引是否有效,如果无效则返回。
交换CmdButtons列表中的拖拽行与目标行的位置。 - DragDrop.DoDragDrop方法启动拖动操作
private void DataGrid_Drop(object sender, DragEventArgs e){DataGrid dataGrid = sender as DataGrid;int b = dataGrid.SelectedIndex;if (dataGrid != null){Point position = e.GetPosition(dataGrid);HitTestResult hitTestResult = VisualTreeHelper.HitTest(dataGrid, position);DependencyObject target = hitTestResult.VisualHit;while (target != null && !(target is DataGridRow)){target = VisualTreeHelper.GetParent(target);}if (target is DataGridRow){DataGridRow row = target as DataGridRow;int i = row.GetIndex();if (b<0 || i < 0 || b >CmdButtons.Count - 1 || i > CmdButtons.Count - 1){return;}CmdButton tmp = CmdButtons[b];CmdButtons[b] = CmdButtons[i];CmdButtons[i] = tmp;}}}private void DataGrid_DragOver(object sender, DragEventArgs e){if (isPressed){ScrollViewer sv = GetScrollViewer(sender as DataGrid);var position = e.GetPosition(sv);if (position.Y >= 330){sv.ScrollToVerticalOffset(sv.VerticalOffset + 15);}if (position.Y<40){sv.ScrollToVerticalOffset(sv.VerticalOffset - 15);}}}private ScrollViewer GetScrollViewer(DataGrid dataGrid){DependencyObject depObject = dataGrid;int i = 0;while (depObject != null){if (depObject is ScrollViewer scrollViewer){return scrollViewer;}depObject = VisualTreeHelper.GetChild(depObject, 0);}return null;}private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e){try{if (e.LeftButton == MouseButtonState.Pressed){isPressed = true;DragDrop.DoDragDrop(sender as DataGrid, new DataGridRow(), DragDropEffects.Move);}if (e.LeftButton == MouseButtonState.Released){isPressed = false;}}catch (Exception ex){throw;}}
这篇关于wpf DataGrid 实现拖拽变换位置,双击拖拽向下自动滚动的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!