本节主要在上节的基础上实现拖拽改变父子节点层级的功能,效果如下:
1、添加全局变量
private Point lastMouseDownPoint;//上一次鼠标左键点击位置
private TreeViewNode targetNode;//目标节点
2、在TreeView控件中加入MouseLeftButtonDown事件
/// <summary>
/// 鼠标左键按下事件响应
/// </summary>
private void TreeView_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
lastMouseDownPoint = e.GetPosition(this.treeView);
}
}
3、在TreeViewItem样式中加入拖拽相关事件
<EventSetter Event="DragEnter" Handler="TreeView_DragEnter"></EventSetter>
<EventSetter Event="DragLeave" Handler="TreeView_DragLeave"></EventSetter>
<EventSetter Event="DragOver" Handler="TreeView_DragEnter"></EventSetter>
<EventSetter Event="Drop" Handler="TreeView_Drop"></EventSetter>
<EventSetter Event="MouseMove" Handler="TreeView_MouseMove"></EventSetter>
相关事件源码:
/// <summary>
/// 拖拽进入,改变字体颜色
/// </summary>
private void TreeView_DragEnter(object sender, DragEventArgs e)
{
TreeViewItem container = GetNearestContainer(e.OriginalSource as UIElement);
if (container != null)
{
container.Foreground = new SolidColorBrush(Colors.Orange);
}
}
/// <summary>
/// 拖拽离