本文代码基本参考WPF Drag and Drop Using Behavior
拖放
拖放操作通常涉及两个参与方:拖动对象所源自的拖动源和接收放置对象的拖放目标。 拖动源和放置目标可能是相同应用程序或不同应用程序中的 UI 元素。
Drag
Drag就是拖动源
public interface IDragable
{
Type DataType { get; }
object Data { get;}
}
Drag的Behavior
这里主要是在按住鼠标同时移动鼠标也就是拖动操作。这里最关键的就是拖动源通过调用静态 DragDrop.DoDragDrop 方法和向其传递传输的数据来启动拖放操作。
public class FrameworkElementDragBehavior : Behavior<FrameworkElement>
{
private bool isMouseClicked = false;
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.MouseLeftButtonDown += new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown);
this.AssociatedObject.MouseLeftButtonUp += new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonUp);
this.AssociatedObject.MouseLeave += new MouseEventHandler(AssociatedObject_MouseMove);
}
void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
isMouseClicked = true;
}
void AssociatedObject_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
isMouseClicked = false;
}
void AssociatedObject_MouseMove(object sender, MouseEventArgs e)
{
if (isMouseClicked)
{
isMouseClicked = false;
//set the item's DataContext as the data to be transferred
IDragable dragObject = this.AssociatedObject.DataContext as IDragable;
if (dragObject != null)
{
DataObject data = new DataObject();
data.SetData(dragObject.DataType, dragObject.Data);
System.Windows.DragDrop.DoDragDrop(this.AssociatedObject, data, DragDropEffects.All);
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.MouseLeftButtonDown -= new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown);
this.AssociatedObject.MouseLeftButtonUp -= new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonUp);
this.AssociatedObject.MouseLeave -= new MouseEventHandler(AssociatedObject_MouseMove);
}
}
Drop
Drop就是拖入的目标,IDropable接口就是实现目标拖入到列表中的操作。
public interface IDropable
{
/// <summary>
/// 拖入的数据类型
/// </summary>
Type DataType { get; }
/// <summary>
/// 拖入到列表中
/// </summary>
/// <param name="data">被拖入的data</param>
void Drop(object data);
/// <summary>
/// 拖入到列表中
/// </summary>
/// <param name="data">被拖入的data</param>
void DropIn(object data, object above, object below);
/// <summary>
/// 是否允许拖入
/// </summary>
/// <param name="dataObject"></param>
/// <returns></returns>
bool CanDrop

本文详细介绍了在WPF中使用Behavior实现拖放功能,包括Drag(拖动源)、Drop(拖入目标)以及针对不同类型控件(如FrameworkElement、TreeView)的特定Drop行为。展示了如何创建和应用Draggable和Dropable接口,以及如何在实际业务场景中操作数据。
最低0.47元/天 解锁文章
2088

被折叠的 条评论
为什么被折叠?



