访问DropHandler
(或与此相关的任何其他类)中的ViewModel属性的最佳实践是什么。在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
ctor中初始化对MainViewModel
的引用后,该引用将传递给DropHandler。这行得通,但是我不确定这是做到这一点的“适当”方法(新手程序员)。应该将DefineDeviceList
集合定义为DropHandler中的一个属性吗?