项目需要实现一个DataGrid拖动排序,于是参考网上一些资源然后,修改了下实现了一个附加属性类,如下

使用方法

<DataGrid
x:Name="shareGrid"
test:DragDropRowBehavior.Enabled="True"
test:DragDropRowBehavior.DropFinish="{Binding TestCommand}" />

DropFinish有在鼠标释放时调用,参数中包含了 拖动的数据,行号,目标行号,目标数据等。

源码:

  public static class DataGridDragDropRowBehavior
{
public delegate Point GetDragDropPosition(IInputElement theElement); public static DependencyProperty DropFinishProperty =
DependencyProperty.RegisterAttached("DropFinish", typeof(ICommand), typeof(DataGridDragDropRowBehavior),
new UIPropertyMetadata(null)); public static void SetDropFinish(UIElement target, ICommand value)
{
target.SetValue(DropFinishProperty, value);
} public static bool GetEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(EnabledProperty);
} public static void SetEnabled(DependencyObject obj, bool value)
{
obj.SetValue(EnabledProperty, value);
} public static readonly DependencyProperty EnabledProperty =
DependencyProperty.RegisterAttached("Enabled", typeof(bool), typeof(DataGridDragDropRowBehavior), new PropertyMetadata(false, OnEnableChanged)); private static void OnEnableChanged(DependencyObject depObject, DependencyPropertyChangedEventArgs e)
{
var dataGrid = depObject as DataGrid; var enable = (bool)e.NewValue;
if (enable)
{
dataGrid.AllowDrop = true;
dataGrid.PreviewMouseLeftButtonDown += DataGrid_PreviewMouseLeftButtonDown;
dataGrid.Drop += DataGrid_Drop;
}
else
{
dataGrid.PreviewMouseLeftButtonDown -= DataGrid_PreviewMouseLeftButtonDown;
dataGrid.Drop -= DataGrid_Drop;
}
} private static void DataGrid_Drop(object sender, DragEventArgs e)
{
DragItem dragitem = e.Data.GetData("DragItem") as DragItem; if (dragitem.RowIndex < )
{
return;
}
DataGrid datagrid = sender as DataGrid;
int index = GetDataGridItemCurrentRowIndex(e.GetPosition, datagrid); //The current Rowindex is -1 (No selected)
if (index < )
{
return;
}
//If Drag-Drop Location are same
if (index == dragitem.RowIndex)
{
return;
} var targetItem = datagrid.Items[index]; DropEventArgs arg = new DropEventArgs();
arg.SourceRowIndex = dragitem.RowIndex;
arg.TargetRowIndex = index;
arg.Data = dragitem.Data;
arg.TargetData = targetItem; var command = (ICommand)datagrid.GetValue(DropFinishProperty);
if (command != null)
{
command.Execute(arg);
}
} private static void DataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGrid datagrid = sender as DataGrid;
var m_prevRowIndex = GetDataGridItemCurrentRowIndex(e.GetPosition, datagrid); if (m_prevRowIndex < )
{
return;
}
datagrid.SelectedIndex = m_prevRowIndex; var selectedItem = datagrid.Items[m_prevRowIndex]; if (selectedItem == null)
{
return;
} DragItem dragItem = new DragItem();
dragItem.RowIndex = m_prevRowIndex;
dragItem.Data = selectedItem;
DataObject data = new DataObject("DragItem", dragItem);
//Now Create a Drag Rectangle with Mouse Drag-Effect
//Here you can select the Effect as per your choice DragDropEffects dragdropeffects = DragDropEffects.Move; if (DragDrop.DoDragDrop(datagrid, data, dragdropeffects) != DragDropEffects.None)
{
//Now This Item will be dropped at new location and so the new Selected Item
datagrid.SelectedItem = selectedItem;
}
} /// <summary>
/// Method checks whether the mouse is on the required Target
/// Input Parameter (1) "Visual" -> Used to provide Rendering support to WPF
/// Input Paraneter (2) "User Defined Delegate" positioning for Operation
/// </summary>
/// <param name="theTarget"></param>
/// <param name="pos"></param>
/// <returns>The "Rect" Information for specific Position</returns>
private static bool IsTheMouseOnTargetRow(Visual theTarget, GetDragDropPosition pos)
{
Rect posBounds = VisualTreeHelper.GetDescendantBounds(theTarget);
Point theMousePos = pos((IInputElement)theTarget);
return posBounds.Contains(theMousePos);
} private static DataGridRow GetDataGridRowItem(DataGrid dataGrid, int index)
{
if (dataGrid.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
{
return null;
}
return dataGrid.ItemContainerGenerator.ContainerFromIndex(index)
as DataGridRow;
} private static int GetDataGridItemCurrentRowIndex(GetDragDropPosition pos, DataGrid dataGrid)
{
int curIndex = -;
for (int i = ; i < dataGrid.Items.Count; i++)
{
DataGridRow itm = GetDataGridRowItem(dataGrid, i);
if (IsTheMouseOnTargetRow(itm, pos))
{
curIndex = i;
break;
}
}
return curIndex;
}
} public class DragItem
{
public int RowIndex { get; set; }
public object Data { get; set; }
} public class DropEventArgs
{
public int SourceRowIndex { get; set; }
public object Data { get; set; } public int TargetRowIndex { get; set; } public object TargetData { get; set; }
}

参考资源:http://www.dotnetcurry.com/wpf/677/wpf-data-grid-row-drag-drop

DataGrid 拖动 附加属性类的更多相关文章

  1. silverlight datagrid绑定匿名类

    原文 http://www.cnblogs.com/luweis/archive/2011/10/21/2220587.html 刚开始遇到的一个问题是这样的,我有一个datagrid,根据不同的条件 ...

  2. datagrid拖动列头更换排列顺序

    在做这个功能的时候在网上找了大量资料,发现都不适用,要不然就是代码太冗余,所以另起炉灶,自己封装了这个函数 下面是完整的代码: <!DOCTYPE html> <html> & ...

  3. 控制EasyUI DataGrid高度

    这次要说的是控制EasyUI的高度,平时我公司的项目,用EasyUI较多,然后datagrid这个组件是用的非常多的.平时我们都是固定高度,常见代码如下:             <table  ...

  4. VS2015中的项目类图

    发现右键项目的时候,是没有类图的. https://msdn.microsoft.com/en-us/library/hyxd8c85.aspx 右键项目--添加--新建项. 选择类图. 然后将整个项 ...

  5. Flutter进阶—点击、拖动和其他手势

    Flutter中的手势系统有两个层次.第一层具有原始指针事件,其描述了穿过屏幕的指针(例如触摸.鼠标和触控笔)的位置和移动.第二层具有手势,其描述由一个或多个指针移动组成的语义动作. 指针指针代表用户 ...

  6. Windows Community Toolkit 4.0 - DataGrid - Part03

    概述 在上面一篇 Windows Community Toolkit 4.0 - DataGrid - Part02 中,我们针对 DataGrid 控件的 Utilities 部分做了详细分享.而在 ...

  7. C# WinForm开发系列 - DataGrid/DataGridView

    在WinForm开发中,DataGrid/DataGridView被广泛使用于绑定数据库中数据进行呈现.整理一些关于DataGrid/DataGridView使用的文章,涉及DataGrid/Data ...

  8. easyui datagrid列拖拽

    <script type="text/javascript"> var cols = [{ field: 'testName', title: '<span cl ...

  9. Easyui datagrid自定义排序

    做项目遇到个关于排序问题,想着在前端排序,正好Easyui有这个功能,所以就拿来用了一下,因为跟官网的Demo不太一样,所以总结一下: 首先这一列是要排序的列(当然,在生产环境,这一列是隐藏的,在开发 ...

随机推荐

  1. 算法,java代码实现打印万年历

      万年历 以1900年1月1号星期一为时间原点 星期日 第一天 星期一 第二天 星期二 第三天 星期三 第四天 星期四 第五天 星期五 第六天 星期六 第七天            1.计算出当前日 ...

  2. EntityFramework默认映射规则

    我不太习惯通过CodeFirst去维护数据库(尽管这是未来实现自动编程的必经之路),还是喜欢通过数据库设计工具如PowerDesigner去建表.如果不想对EF的实体和数据表做什么映射的话,就要注意默 ...

  3. set&enum小结(database)

    今天发现mysql中有set这种数据类型,工作的业务中也使用到了.网上查阅资料后,小结一下 先总结一下两者的分别 set和enum类似表单中的多选和单选,set和enum在数据库内部是用整数表示的,显 ...

  4. nginx添加编译lua模块

    一 .安装LuaJit 1.下载LuaJit # wget http://luajit.org/download/LuaJIT-2.0.5.tar.gz 2.编译安装 # tar xzvf LuaJI ...

  5. python_如何对迭代器进行切片操作

    案例: 对于某个文件,我只想读取到其中100~200行之间的内容,是否可以通过切片的方式进行读取? 我想: f = open() f[100:200] 可行? 如何解决这个问题? 方法1: 全部读取到 ...

  6. JS动态获取当前时间

    HTML部分: <div class="div"> <div id="div"> </div> </div> C ...

  7. <%@include file="a.jsp"%> jsp引用jsp文件时候注意

    被包含的a.jsp文件:    a.jsp文件的page指令要么不要写.要么与主jsp文件的page指令一样.

  8. 怎样查看MYSQL数据库的端口号

    show variables like '%port%';

  9. 【转】globk中的控制文件

    globk_comb.cmd * This group must be first eq_file ../tables/eq_renames make_svs ../tables/sat1.apr c ...

  10. GO开发:用go写个日志监控系统

    日志收集系统架构 1.项目背景 a. 每个系统都有日志,当系统出现问题时,需要通过日志解决问题 b. 当系统机器比较少时,登陆到服务器上查看即可满足 c. 当系统机器规模巨大,登陆到机器上查看几乎不现 ...