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

淺唱寂寞╮ 提交于 2019-12-25 08:08:52

问题


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);
listBox.Items.Add(files);

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?


回答1:


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)
{
    listBox.Items.Add(path);
}



回答2:


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">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" Foreground="Green" FontSize="16" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>


来源:https://stackoverflow.com/questions/41323730/how-do-i-drag-n-drop-files-into-a-listbox-with-it-showing-the-file-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!