Как лучше всего обращаться к свойству ViewModel в DropHandler
(или в любом другом классе). В MainViewModel
у меня есть следующий код:
public DefineDeviceListDropHandler DefineDeviceDropHandler { get; set; }
private ObservableCollection<Device> _defineDeviceList;
public ObservableCollection<Device> DefineDeviceList
{
get
{
return _defineDeviceList;
}
set
{
_defineDeviceList = value;
OnPropertyChanged();
}
}
Свойство DropHandler инициализируется в конструкторе MainViewModel
:
public MainViewModel()
{
DefineDeviceDropHandler = new DefineDeviceListDropHandler(this);
this.PropertyChanged += ViewModelPropertyChanged;
}
DropHandler определен в отдельном классе:
using GongSolutions.Wpf.DragDrop;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using NollTabEllen.Models;
namespace NollTabEllen.ViewModel
{
public class DefineDeviceListDropHandler : IDropTarget
{
private MainViewModel mvm;
public DefineDeviceListDropHandler(MainViewModel mainViewModel)
{
mvm = mainViewModel;
}
void IDropTarget.DragOver(IDropInfo dropInfo)
{
if (dropInfo.DragInfo.SourceItems == null)
return;
if (dropInfo.DragInfo.SourceCollection is ObservableCollection<Device> deviceSourceCollection)
{
if (deviceSourceCollection == mvm.DefineDeviceList) // Check if it is a specific collection in viewmodel
{
dropInfo.DropTargetAdorner = DropTargetAdorners.Insert;
dropInfo.Effects = DragDropEffects.Move;
}
}
}
}
}
Как вы можете видеть, ссылка на MainViewModel
передается в DropHandler при инициализации в MainViewModel
ctor. Это работает, но я не уверен, что это «правильный» способ сделать это (начинающий программист). Следует ли вместо этого коллекцию DefineDeviceList
определять как свойство в DropHandler?