How do I drag n drop files into a ListBox with it showing the file path?


Currently when I drag n drop files into my ListBox using the Window_Drop event I have this code.

string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop, true);

Which works fine in WinForm it prints out the path of the file I just dragged and dropped into it as a item to the ListBox.
However when I do the same thing in WPF I get this

String[] Array

as an output instead of the path.

Now I know that code from WinForm doesn't exactly transfer over to WPF but I would guess it's pretty similar?

How do I correctly drag and drop an item to the ListBox with it showing the path of the file?

Show source
| c#   | wpf   | listbox   | winforms   | drag-and-drop   2016-12-25 19:12 2 Answers

Answers ( 2 )

  1. 2016-12-25 20:12

    Instead of adding the string[] to the ListBox you will need to add a string from a specified index of the array like this listBox.Items.Add(files[yourIndex]);

    EDIT: If you're going to import multiple files at once without adding more from the same array you should do:

    foreach(string path in files)
  2. 2016-12-26 19:12

    You could set the ItemsSource property of the ListBox to your string[]:

    string[] files = (string[]) e.Data.GetData(DataFormats.FileDrop, true);
    listBox.ItemsSource = files;

    In WPF you typically bind the ItemsSource property of an ItemsControl (such as a ListBox) to an IEnumerable<T> and define an ItemTemplate in your XAML markup that defines the appearance of each object of type T:

    WPF ListBox using ItemsSource and ItemTemplate

    <ListBox x:Name="listBox">
                <TextBlock Text="{Binding}" Foreground="Green" FontSize="16" />
◀ Go back