Search code examples
c#wpflistviewlistviewitem

Drop Item into Specific Index in ListView in WPF C#


I have a list of files in a ListView in WPF. Users can drag files onto the list view, and right now they are just appended to the end of the list. Is it possible to insert the file into the ListView right where the user dropped it?


Solution

  • WPF isn't really designed to be used that way. While you can brute force add ListViewItem's directly to the ListView, the way it's really supposed to work is that you have a collection of some kind (ObservableCollection<FileInfo> would work well) and bind the ListView's ItemsSource property to that collection.

    Then the answer is simple. Instead of the Add method, you use the Insert method of the collection which takes an index.

    As for finding which ListViewItem the mouse event occurred over, you could use the VisualTreeHelper.HitTest method.