在DropHandler中访问ViewModel属性的最佳做法?

时间:2019-01-05 12:34:20

标签: c# mvvm

访问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中的一个属性吗?

0 个答案:

没有答案