Skip to content

Instantly share code, notes, and snippets.

@ousttrue
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ousttrue/d19043653b18abd4dc27 to your computer and use it in GitHub Desktop.
Save ousttrue/d19043653b18abd4dc27 to your computer and use it in GitHub Desktop.
Behavior for file & url drop
public class FileDropBehavior : Behavior<FrameworkElement>
{
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Using a DependencyProperty as the backing store for Command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(FileDropBehavior)
, new PropertyMetadata(null));
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.AllowDrop=true;
this.AssociatedObject.PreviewDragOver += OnPreviewDragOver;
this.AssociatedObject.Drop += OnDrop;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.PreviewDragOver -= OnPreviewDragOver;
this.AssociatedObject.Drop -= OnDrop;
}
private void OnPreviewDragOver(object sender, System.Windows.DragEventArgs e)
{
if (e.Data.GetDataPresent(System.Windows.DataFormats.FileDrop, true))
{
e.Effects = System.Windows.DragDropEffects.Copy;
}
else if (e.Data.GetDataPresent("UniformResourceLocator"))
{
e.Effects = DragDropEffects.Link;
}
else
{
e.Effects = System.Windows.DragDropEffects.None;
}
e.Handled = true;
}
IEnumerable<Uri> ToUrlList(IDataObject data)
{
if (data.GetDataPresent(DataFormats.FileDrop))
{
return (data.GetData(DataFormats.FileDrop) as string[])
.Select(s => new Uri(s))
;
}
else
{
var url = new Uri(data.GetData(DataFormats.Text).ToString());
return new Uri[] { url };
}
}
private void OnDrop(object sender, System.Windows.DragEventArgs e)
{
if (Command == null) return;
if (!Command.CanExecute(e)) return;
var urllist = ToUrlList(e.Data);
if (urllist == null) return;
Command.Execute(urllist);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment