WPF DataGrid 行拖拽实现

本文介绍了如何实现WPF DataGrid的行拖拽功能。通过自定义DataGrid控件,添加Popup并利用AutoGeneratingColumn事件生成模板。同时,利用Drop和MouseLeftButtonDown事件实现拖放操作。需注意将DataGrid的AllowDrop属性设为True,并使用Blend辅助编辑样式。
摘要由CSDN通过智能技术生成

        DataGrid行拖拽需要我们自己去实现,我也是模仿网上例子进行改造。

        大概思路,我们需要自定义一个DataGrid的控件,然后再样式中加入一个Popup(作为被拖拽行的显示),我们要弄成所有都可以使用,就需要将Popup内容显示的模板实现自动生成,我们可以在AutoGeneratingColumn事件里实现,我是使用XMAL的方式保存所有的控件,然后赋值给我们自定义的一个DataTemplate属性。

        拖拽主要用到Drop、MouseLeftButtonDown事件。(需要将DataGird的AllowDrop设置为True)。

        伪代码(自己自行去完整):

<Popup AllowsTransparency = "True" IsOpen = "{Binding IsPopup, RelativeSource = "{RelativeSource  Mode = FindAncesTor, AncestorType = {x:Type xxxxxx}}}" 
Foucusable = "False" IsHitestVisible = "False" Placement = "RelativePoint"
PlacementRectangle = "{Binding PopupPlacementRectangle, RelativeSource = "{RelativeSource  Mode = FindAncesTor, AncestorType = {x:Type xxxxxx}}}" >
    <Grid>
 
WPF DataGrid 支持拖拽实现方式如下: 1. 首先,需要在 DataGrid 控件上启用拖拽功能,可以通过设置 CanUserSortColumns 和 CanUserReorderColumns 属性为 true 来实现。 2. 然后,需要为 DataGrid 控件的设置拖拽事件,可以使用 PreviewMouseMove 和 PreviewMouseLeftButtonDown 事件来实现。 3. 在 PreviewMouseLeftButtonDown 事件中,需要使用 VisualTreeHelper.GetParent 方法来获取所选DataGridRow 控件。 4. 在 PreviewMouseMove 事件中,需要使用 DragDrop.DoDragDrop 方法来开始拖拽操作,并设置拖拽数据的格式和数据对象。 5. 最后,在 DataGrid 控件上订阅 Drop 事件,实现拖拽功能。 示例代码如下: ```xml <DataGrid CanUserSortColumns="True" CanUserReorderColumns="True" PreviewMouseMove="DataGrid_PreviewMouseMove" PreviewMouseLeftButtonDown="DataGrid_PreviewMouseLeftButtonDown" Drop="DataGrid_Drop"> </DataGrid> ``` ```c# private void DataGrid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { DataGridRow row = FindAncestor<DataGridRow>((DependencyObject)e.OriginalSource); if (row != null) { // 设置拖拽数据的格式和数据对象 DataObject dragData = new DataObject(DataFormats.Serializable, row.DataContext); DragDrop.DoDragDrop(row, dragData, DragDropEffects.Move); } } private void DataGrid_PreviewMouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { DataGridRow row = FindAncestor<DataGridRow>((DependencyObject)e.OriginalSource); if (row != null) { // 开始拖拽操作 DragDrop.DoDragDrop(row, row.DataContext, DragDropEffects.Move); e.Handled = true; } } } private void DataGrid_Drop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.Serializable)) { // 获取拖拽数据的数据对象 var data = e.Data.GetData(DataFormats.Serializable) as YourDataObject; if (data != null) { // 处理拖拽逻辑 // ... } } } private static T FindAncestor<T>(DependencyObject current) where T : DependencyObject { do { if (current is T ancestor) { return ancestor; } current = VisualTreeHelper.GetParent(current); } while (current != null); return null; } ``` 注意,在上面的示例代码中,要根据实际情况修改拖拽操作中的数据格式和数据对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值