在树视图中拖放
Posted
技术标签:
【中文标题】在树视图中拖放【英文标题】:Drag & Drop in Treeview 【发布时间】:2010-11-04 19:12:01 【问题描述】:我正在尝试在树形视图中拖放文件,但我不知道如果我运行它并尝试拖动文件,它为什么会崩溃。
下面的代码是我尝试过的。请帮忙。
private void TreeViewItem_Drop( object sender, DragEventArgs e)
TreeViewItem treeViewItem = e.Source as TreeViewItem;
TreeViewItem obj = e.Data.GetData(typeof(TreeViewItem)) as TreeViewItem;
if ((obj.Parent as TreeViewItem) != null)
(obj.Parent as TreeViewItem).Items.Remove(obj);
else
treeViewItem.Items.Remove(obj);
treeViewItem.Items.Insert(0, obj);
e.Handled = true;
private void TreeViewItem_MouseLeftButtonDown( object sender,MouseButtonEventArgs e)
DependencyObject dependencyObject = _treeview.InputHitTest(e.GetPosition(_treeview)) as DependencyObject;
Debug.Write(e.Source.GetType().ToString());
if (dependencyObject is TextBlock)
TreeViewItem treeviewItem = e.Source as TreeViewItem;
DragDrop.DoDragDrop(_treeview, _treeview.SelectedValue, DragDropEffects.Move);
e.Handled = true;
【问题讨论】:
【参考方案1】:这篇文章很有帮助。 Drag drop wpf
此代码也可能对您有用。
Point _startPoint;
bool _IsDragging = false;
void TemplateTreeView_PreviewMouseMove(object sender, MouseEventArgs e)
if (e.LeftButton == MouseButtonState.Pressed ||
e.RightButton == MouseButtonState.Pressed && !_IsDragging)
Point position = e.GetPosition(null);
if (Math.Abs(position.X - _startPoint.X) >
SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(position.Y - _startPoint.Y) >
SystemParameters.MinimumVerticalDragDistance)
StartDrag(e);
void TemplateTreeView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
_startPoint = e.GetPosition(null);
private void StartDrag(MouseEventArgs e)
_IsDragging = true;
object temp = this.TemplateTreeView.SelectedItem;
DataObject data = null;
data = new DataObject("inadt", temp);
if (data != null)
DragDropEffects dde = DragDropEffects.Move;
if (e.RightButton == MouseButtonState.Pressed)
dde = DragDropEffects.All;
DragDropEffects de = DragDrop.DoDragDrop(this.TemplateTreeView, data, dde);
_IsDragging = false;
【讨论】:
感谢 Erin 代码确实帮助我们意识到出了什么问题。在我的 MousePreviewDown 中有几件事是错误的,比如我没有使用 Math.Abs()。抱歉反馈来晚了:) 如果您愿意,请将其标记为答案。以上是关于在树视图中拖放的主要内容,如果未能解决你的问题,请参考以下文章
在具有 UITableView 的 UICollectionView 中拖放