Если вы используете структуру MVVM с Dependency Injection, создайте открытый класс. Вот пример того, что я сделал.
using System.Windows;
using System.Windows.Input;
namespace Test.Common
{
public class Behaviors
{
public static readonly DependencyProperty DropFileCommandProperty =
DependencyProperty.RegisterAttached("DropFileCommand", typeof(ICommand),
typeof(Behaviors), new FrameworkPropertyMetadata(
new PropertyChangedCallback(DropFileCommandChanged)));
private static void DropFileCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
FrameworkElement element = (FrameworkElement)d;
element.Drop += Element_DropFile;
}
private static void Element_DropFile(object sender, DragEventArgs e)
{
FrameworkElement element = (FrameworkElement)sender;
ICommand command = GeDropFileCommand(element);
command.Execute(e);
}
public static void SetDropFileCommand(UIElement element, ICommand value)
{
element.SetValue(DropFileCommandProperty, value);
}
public static ICommand GeDropFileCommand(UIElement element)
{
return (ICommand)element.GetValue(DropFileCommandProperty);
}
}
}
Теперь вы можете ссылаться на ваш класс следующим образом.
<Window x:Class="Test.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:common="clr-namespace:Test.Common"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
AllowDrop="True"
common:Behaviors.DropFileCommand="{Binding DropFile}"
Title="{Binding Title}">
<Grid>
</Grid>
</Window>
Теперь в вашей ViewModel вы можете делать следующее.
using Prism.Commands;
using Prism.Mvvm;
using System.Windows;
namespace Test.Views
{
public class MainWindowViewModel : BindableBase
{
private string _title = "TestDrop";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
public MainWindowViewModel()
{
DropFile = new DelegateCommand<DragEventArgs>(dropFile);
}
public DelegateCommand<DragEventArgs> DropFile { get; }
private void dropFile(DragEventArgs obj)
{
var files = obj.Data.GetData(DataFormats.FileDrop, true) as string[];
//implement rest of code here
}
}
}