拖放自定义控件不起作用

时间:2016-07-24 18:33:30

标签: c# wpf mvvm

我已经构建了一个自定义ListView以允许我拖放。在其他问题和博客文章的帮助下,我已经走到了这一步。

我在MVVM的实现中使用了UserControl,但在构建实际的自定义ListView时,我只是使用了后面的代码。因为我认为这会更容易。

如何实现以下代码以添加到ViewModel ICollection?

更新

请注意,我认为发生这种情况的原因是因为我尝试将object添加到ObservableCollection<person>();

异常:

  

使用ItemsSource时,操作无效。使用ItemsControl.ItemsSource访问和修改元素。

XAML:实施:

<controls:DragNDropListView 
            x:Name="ListView"
            ItemsSource="{Binding Persons}"
            DragDropEffects="Copy"
            DisplayMemberPath="Name"></controls:DragNDropListView>

<controls:DragNDropListView 
            x:Name="ListView1"
            Grid.Column="1" 
            ItemsSource="{Binding Persons1}" 
            DisplayMemberPath="Name"
            DragDropEffects="Copy"/>

视图模型:

public class ViewModel 
{
    public ViewModel()
    {
        Persons = new ObservableCollection<Person>();
        Persons1 = new ObservableCollection<Person>();
        Persons.Clear();
        Persons1.Clear();
        foreach (var person in Data.People().ToList())
        {
            Persons.Add(person);
            Persons1.Add(person);
        }

    }
    public ObservableCollection<Person> Persons { get; set; }
    public ObservableCollection<Person> Persons1 { get; set; }
}

拖动代码:

private void OnMouseMove(object sender, MouseEventArgs e)
    {
        Point mousePos = e.GetPosition(null);
        Vector diff = _startPoint - mousePos;
        if (e.LeftButton == MouseButtonState.Pressed &&
            (Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
             Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
        {
            if (ListView != null)
            {
                ListViewItem listViewItem =
                    FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);
                if (listViewItem != null)
                {
                    var item = ListView.ItemContainerGenerator.ItemFromContainer(listViewItem);  //NOTE:this is an object not a Person like observeablecollection in ViewModel.
                    DataObject dragData = new DataObject("myFormat", item);
                    DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects); 
                }
            }
        }
    }

删除抛出异常的代码:

private void OnDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent("myFormat"))
        {
            var item = e.Data.GetData("myFormat");
            if (item != null)
            {
                Items.Add(item);//this is where it throws exception
            }
        }
    }

0 个答案:

没有答案