WPF C#: Rearrange items in listbox via drag and drop?

I've tried create one using observablecollection, have a look.

I've tried create one using observablecollection, have a look ObservableCollection _empList = new ObservableCollection(); public Window1() { InitializeComponent(); _empList . Add(new Emp("1", 22)); _empList . Add(new Emp("2", 18)); _empList .

Add(new Emp("3", 29)); _empList . Add(new Emp("4", 9)); _empList . Add(new Emp("5", 29)); _empList .

Add(new Emp("6", 9)); listbox1. DisplayMemberPath = "Name"; listbox1. ItemsSource = _empList; Style itemContainerStyle = new Style(typeof(ListBoxItem)); itemContainerStyle.Setters.

Add(new Setter(ListBoxItem. AllowDropProperty, true)); itemContainerStyle.Setters. Add(new EventSetter(ListBoxItem.

PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(s_PreviewMouseLeftButtonDown))); itemContainerStyle.Setters. Add(new EventSetter(ListBoxItem. DropEvent, new DragEventHandler(listbox1_Drop))); listbox1.

ItemContainerStyle = itemContainerStyle; } Drag and drop process void s_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (sender is ListBoxItem) { ListBoxItem draggedItem = sender as ListBoxItem; DragDrop. DoDragDrop(draggedItem, draggedItem. DataContext, DragDropEffects.

Move); draggedItem. IsSelected = true; } } void listbox1_Drop(object sender, DragEventArgs e) { Emp droppedData = e.Data. GetData(typeof(Emp)) as Emp; Emp target = ((ListBoxItem)(sender)).

DataContext as Emp; int removedIdx = listbox1.Items. IndexOf(droppedData); int targetIdx = listbox1.Items. IndexOf(target); if (removedIdx remIdx) { _empList.

Insert(targetIdx, droppedData); _empList. RemoveAt(remIdx); } } } Note: one thing sucks in the implementation is since it use the PreviewMouseLeftButtonDown event, the dragged item looks like not selected and also for an easier implementation the drop target is the list box items and not the listbox itself - might need a better solution for this.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions