using System.Windows;
using Microsoft.Xaml.Behaviors;
///
/// 拖拽文件事件
///
/// DropFileBehaviors Data="{Binding FileNames,Mode=OneWayToSource}"从依赖属性传到源属性,通过源属性实现Mvvm
/// 设置窗口属性AllowDrop,在上层覆盖一个面板如Grid,设置窗口的DropEnter和DropLeave(EventTrigger)事件,控制其显隐以及控制Drop事件后隐藏(ChangePropertyAction)
class DropFileBehavior : Behavior
{
public string[] Data
{
get { return (string[])GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register(nameof(Data), typeof(string[]), typeof(DropFileBehavior), new PropertyMetadata(null));
protected override void OnAttached()
{
AssociatedObject.AllowDrop = true;
AssociatedObject.Drop += DropHandler;
}
private void DropHandler(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
Data = (string[])e.Data.GetData(DataFormats.FileDrop);
}
}
protected override void OnDetaching()
{
AssociatedObject.Drop -= DropHandler;
}
protected override void OnChanged()
{
base.OnChanged();
}
}