- 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;
}
}
文章来源地址https://www.toymoban.com/news/detail-801647.html
文章来源:https://www.toymoban.com/news/detail-801647.html
到了这里,关于wpf DataGrid 实现拖拽变换位置,双击拖拽向下自动滚动的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!