【WPF】 实现Treeview 的拖拽
实现方式有两种。
方式一:通过重载事件来进行的
参考项目源码:https://files.cnblogs.com/ruicky/Wpf-TreeView-%E5%85%A8%E8%83%BD%E5%AE%9E%E7%8E%B0%E6%8B%96%E6%8B%BD.zip
优点:调用到自己的项目中方式简单。随意拖动
缺点:难以添加限制对于一些节点不能拖动的设置性弱
方式二:通过写Treeview的事件来进行拖动
前台:
View Code
<TreeView Name="tvRequire" BorderThickness="1" MouseDown="tvRequire_MouseDown" MouseMove="tvRequire_MouseMove" DragEnter="TheTreeView_CheckDropTarget" DragLeave="TheTreeView_CheckDropTarget" DragOver="TheTreeView_CheckDropTarget" Drop="tvRequire_Drop" > </TreeView>
后台:
View Code
private Point _lastMouseDown; private void tvRequire_MouseDown(object sender, MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { _lastMouseDown = e.GetPosition(tvRequire); } } private void tvRequire_MouseMove(object sender, MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { Point currentPosition = e.GetPosition(tvRequire); if ((Math.Abs(currentPosition.X - _lastMouseDown.X) > 2.0) || (Math.Abs(currentPosition.Y - _lastMouseDown.Y) > 2.0)) { if ((tvRequire.SelectedItem as TreeViewItem) != null) { DragDropEffects finalDropEffect = DragDrop.DoDragDrop(tvRequire.SelectedItem as TreeViewItem, sender, DragDropEffects.Move); } } } } private void TheTreeView_CheckDropTarget(object sender, DragEventArgs e) { if (e.Source as TreeViewItem != null) { if (!IsValidDropTarget((e.Source as TreeViewItem).Tag)) { e.Effects = DragDropEffects.None; } } e.Handled = true; } //检查是否能够拖 private bool IsValidDropTarget(object id) { bool res = false; if (id != null) { //根据各自需求来写 } return res; } //Drop 进行保存 private void tvRequire_Drop(object sender, DragEventArgs e) { TreeViewItem treeViewItemParent = new TreeViewItem(); if (e.Source as EditableTextBlock != null) { treeViewItemParent = (e.Source as EditableTextBlock).Parent as TreeViewItem;//().Parent as TreeViewItem if (tvRequire.SelectedItem as TreeViewItem == (e.Source as EditableTextBlock).Parent as TreeViewItem) { return; } } else { treeViewItemParent = e.Source as TreeViewItem; if (tvRequire.SelectedItem as TreeViewItem == e.Source as TreeViewItem) { return; } } //进行增加删除功能 TreeViewItem itemRemoved = tvRequire.SelectedItem as TreeViewItem; CusRequireInfo cusRequireInfo = BLLCusRequire.GetModel(Convert.ToInt32(itemRemoved.Tag)); if (cusRequireInfo.ParentId == 0) { tvRequire.Items.Remove(itemRemoved); } else { (itemRemoved.Parent as TreeViewItem).Items.Remove (itemRemoved); } (treeViewItemParent).Items.Add(itemRemoved); cusRequireInfo.ParentId = Convert.ToInt32 (treeViewItemParent.Tag); BLLCusRequire.Update(cusRequireInfo); }
PS:主要有三个方法体 tvRequire_MouseDown(开始记录坐标) tvRequire_MouseMove(指定拖动效果操作)TheTreeView_CheckDropTarget(用来检查是否可拖动) tvRequire_Drop (用来进行拖动后的保存)
优点:能够自定义的限制拖拽条件,比较容易理解
缺点:代码量多,复用率低
转载请注明出处: http://www.cnblogs.com/ruicky/archive/2013/01/21/2869206.html
作者:ruicky
出处:http://www.cnblogs.com/ruicky/
欢迎任何形式的转载,未经作者同意,请保留此段声明!