Hi,@Amelia Moseley. To ensure that the selection is preserved during the drag-and-drop operation, you could use the following code to preserve the selection.
The following code handles the mouse events and drag-and-drop operations for transferring items from the ListView to the TreeView.
xaml:
<ListView x:Name="taskListView" AllowDrop="True" PreviewMouseLeftButtonDown="OnPreviewMouseLeftButtonDown" MouseMove="OnMouseMove" SelectionMode="Multiple">
codebedhind:
private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DependencyObject originalSource = e.OriginalSource as DependencyObject;
ListViewItem clickedItem = FindVisualParent<ListViewItem>(originalSource);
if (clickedItem != null && clickedItem.IsSelected)
{
clickedItem.IsSelected = false;
}
}
private void OnMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
List<Task> taskList = new List<Task>();
foreach (Task task in taskListView.SelectedItems)
{
taskList.Add(task);
}
DataObject data = new DataObject(taskList);
DragDrop.DoDragDrop(taskListView, data, DragDropEffects.Move);
}
}
private void OnDropEvent(object sender, DragEventArgs e)
{
Type type = typeof(List<Task>);
List<Task> selectedItems = e.Data.GetData(type) as List<Task>;
foreach (Task task in selectedItems)
{
TreeViewItem treeViewItem = new TreeViewItem();
treeViewItem.Header = task.Headline;
TreeViewSourceItems.Add(treeViewItem);
ListViewSourceItems.Remove(task);
ICollectionView dataView = CollectionViewSource.GetDefaultView(taskListView.ItemsSource);
dataView.Refresh();
dataView = CollectionViewSource.GetDefaultView(taskTreeView.ItemsSource);
dataView.Refresh();
}
}
private static T FindVisualParent<T>(DependencyObject obj) where T : DependencyObject
{
while (obj != null)
{
if (obj is T parent)
{
return parent;
}
obj = VisualTreeHelper.GetParent(obj);
}
return null;
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.