如何正确使用Data.GetData()作为父类

时间:2017-05-17 16:21:50

标签: c# wpf

我目前正试图为我的列表框实施拖放操作。我需要使用被拖动的元素。

每个拖动的对象都继承了Caliburn Micro的屏幕和我的BaseViewModel

例如

BaseViewModel : Screen

ListBoxItem1 DataContext = PersonViewModel : BaseViewModel
ListBoxItem2 DataContext = BusinessViewModel : BaseViewModel

private void ListBoxItem_DropEvent(object sender, DragEventArgs e)
{
    if (sender is ListBoxItem)
    {
        var source = e.Data.GetData(typeof(PersonViewModel)) as PersonViewModel ;
        var target = ((ListBoxItem)(sender)).DataContext as BusinessViewModel;

        int sourceIndex = Items.Items.IndexOf(source);
        int targetIndex = Items.Items.IndexOf(target);

        Move(source, sourceIndex, targetIndex);
    }
}

所以我现在遇到的问题是我不想指定PersonViewModel / BusinessViewModel我试图通过使用继承值获取typeof希望BaseViewModel或Screen。我可以得到一些提示或建议

我尝试了下面的解决方案,但他们将我归还。

var test = e.Data.GetData(typeof(BaseViewModel)) as BaseViewModel;
var test1 = e.Data.GetData(typeof(Screen)) as Screen;

上一个鼠标事件

private void PreviewMouseMove(object sender, MouseEventArgs e)
{
    Point point = e.GetPosition(null);
    Vector diff = _dragStartPoint - point;
    if (e.LeftButton == MouseButtonState.Pressed &&
        (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
            Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
    {
        var lb = sender as ListBox;
        var lbi = FindVisualParent<ListBoxItem>(((DependencyObject)e.OriginalSource));
        if (lbi != null)
        {
            DragDrop.DoDragDrop(lbi, lbi.DataContext, DragDropEffects.Move);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

试试这个:

var test = e.Data.GetData(e.Data.GetFormats()[0]) as BaseViewModel;