Перетаскивание с ListView WPF не удалось с помощью ItemSource - PullRequest
0 голосов
/ 03 июля 2018

У меня есть ListView с ItemSource:

public ObservableCollection<MyObject> List;

А мой ListView заполнен несколькими объектами.

Теперь я хочу добавить опцию, чтобы изменить мой ListViewItems через Дарга, поэтому я нашел это решение: https://fxmax.wordpress.com/2010/10/05/wpf/

И после добавления кода в мой проект у меня есть только одна проблема, которая вызывает сбой:

private void BeginDrag(MouseEventArgs e)
        {
            ListView listView = this.listView;
            ListViewItem listViewItem = FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);

            if (listViewItem == null)
                return;

            // get the data for the ListViewItem
            MyObject name = (MyObject)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);

            //setup the drag adorner.
            InitialiseAdorner(listViewItem);

            //add handles to update the adorner.
            listView.PreviewDragOver += listView_PreviewDragOver;
            listView.DragLeave += listView_DragLeave;
            listView.DragEnter += listView_DragEnter;

            DataObject data = new DataObject("myFormat", name);
            DragDropEffects de = DragDrop.DoDragDrop(this.listView, data, DragDropEffects.Move);

            //cleanup 
            listView.PreviewDragOver -= listView_PreviewDragOver;
            listView.DragLeave -= listView_DragLeave;
            listView.DragEnter -= listView_DragEnter;

            if (_adorner != null)
            {
                AdornerLayer.GetAdornerLayer(listView).Remove(_adorner);
                _adorner = null;
            }
        }

В этой строке:

DragDropEffects de = DragDrop.DoDragDrop(this.listView, data, DragDropEffects.Move);

System.InvalidOperationException: 'Операция недопустима, пока ItemsSource используется. Доступ и изменение элементов с ItemsControl.ItemsSource вместо. '

Я вижу, это потому, что я использую ItemSource, но не знаю, что изменить.

Есть предложения?

1 Ответ

0 голосов
/ 04 июля 2018

Начиная с примера кода, который вы связали на другом сайте, я внес некоторые изменения и смог исправить решение для работы с ItemsSource.

Внесены следующие изменения: - в MainWindow.xaml

            <ListView ItemsSource="{Binding List}"
              x:Name="listView"

- в MainWindow.xaml.cs

 private void ListViewDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent("myFormat"))
        {
            MyObject name = e.Data.GetData("myFormat") as MyObject;
            ListViewItem listViewItem = FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);
            ObservableCollection<MyObject> myArray = listView.ItemsSource as ObservableCollection<MyObject>;

            if (listViewItem != null && listViewItem.DataContext is MyObject)
            {
                MyObject dropLocation = (MyObject)listViewItem.DataContext;
                int index = myArray.IndexOf(dropLocation);

                if (index >= 0)
                {
                    myArray.Remove(name);
                    myArray.Insert(index, name);
                }
            }
            else
            {
                myArray.Remove(name);
                myArray.Add(name);
            }
        }
    }

...

private void BeginDrag(MouseEventArgs e)
    {
        ListView listView = this.listView;
        ListViewItem listViewItem =
            FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);

        if (listViewItem == null)
            return;

        MyObject selectedItem = (MyObject)listViewItem.DataContext;

        //setup the drag adorner.
        InitialiseAdorner(listViewItem);

        //add handles to update the adorner.
        listView.PreviewDragOver += ListViewDragOver;
        listView.DragLeave += ListViewDragLeave;
        listView.DragEnter += ListViewDragEnter;

        DataObject data = new DataObject("myFormat", selectedItem);
        DragDropEffects de = DragDrop.DoDragDrop(this.listView, data, DragDropEffects.Move);

        //cleanup 
        listView.PreviewDragOver -= ListViewDragOver;
        listView.DragLeave -= ListViewDragLeave;
        listView.DragEnter -= ListViewDragEnter;

        if (_adorner != null)
        {
            AdornerLayer.GetAdornerLayer(listView).Remove(_adorner);
            _adorner = null;
        }
    }

Сами изменения используют концепцию MyObject в качестве полезной нагрузки вместо строки и ObservableCollection в качестве массива, в котором вы вносите изменения, вместо IEnumerable.

Надеюсь, это решит вашу проблему.

...