Using the code
To use the code just download it, open the project using VS 2008, compile and run.
Use drag and drop to re-order the items in the list.
Brief Code Description
There are basically 3 files containing the code: Shape.cs, Window1.xaml and Window.xaml.cs
File Shape.cs contains definition for very simple objects that are used as items behind the ListView. Each item has name and number of sides as properties.
File Window1.xaml contains xaml representing a very simple Window with ListView control in it. ListView's ItemsSource property is set to point to a collection of Shape objects.
File Window1.xaml.cs contains all the C# plumbing and the functions that actually do drag and drop:
ListView1_PreviewMouseLeftButtonDown - originates the drag operation.
ListView1_Drop - completes the drop operation.
Using event argument GetPosition function to determine current mouse position
Both DragEventArgs and MouseButtonEventArgs classes have function
Point GetPosition(IInputElement)
That returns the current mouse position with respect to the Visual element (passed to the function as the argument). Since DragEventArgs and MouseButtonEventArgs do not have a common superclass or interface that defines GetPosition function, I pass wrote the code that takes GetPosition function as a delegate in order to be able to re-use it for both classes. Here is the functionality that returns index of the current item in the list:
int GetCurrentIndex(GetPositionDelegate getPosition)
{
int index = -1;
for (int i = 0; i < this.ListView1.Items.Count; ++i)
{
ListViewItem item = GetListViewItem(i);
if (this.IsMouseOverTarget(item, getPosition))
{
index = i;
break;
}
}
return index;
}
bool IsMouseOverTarget( Visual target, GetPositionDelegate getPosition)
{
Rect bounds = VisualTreeHelper.GetDescendantBounds( target );
Point mousePos = getPosition((IInputElement) target);
return bounds.Contains( mousePos );
}
GetPositionDelegate is defined as
delegate Point GetPositionDelegate(IInputElement element);
Here is how the function GetCurrentIndex is called: From ListView1_Drop function - responsible for dropping operation. (This function uses DragEventArgs):
void ListView1_Drop(object sender, DragEventArgs e)
{
...
int index = this.GetCurrentIndex(e.GetPosition);
...
}
From ListView1_PreviewMouseLeftButtonDown function - responsible for starting drag operation. (This function uses MouseButtonEventArgs):
void ListView1_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
...
oldIndex = this.GetCurrentIndex(e.GetPosition);
...
}
History