简体   繁体   English

如何将n个拖放文件拖到显示文件路径的ListBox中?

[英]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. 当前,当我使用Window_Drop事件将n个拖放文件拖到我的ListBox中时,我有此代码。

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. 在WinForm中可以正常工作,它可以打印出我刚刚拖放到其中的文件的路径,并将其作为项目放入ListBox。
However when I do the same thing in WPF I get this 但是,当我在WPF中做同样的事情时,我得到了

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? 现在我知道WinForm的代码不会完全转移到WPF,但我想它非常相似吗?

How do I correctly drag and drop an item to the ListBox with it showing the path of the file? 如何正确地将一个项目拖放到ListBox并显示文件的路径?

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]); 无需将string[]添加到ListBox中,您需要从数组的指定索引中添加一个字符串,例如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);
}

You could set the ItemsSource property of the ListBox to your string[]: 您可以将ListBox的ItemsSource属性设置为您的字符串[]:

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中,通常将ItemsControl(例如ListBox)的ItemsSource属性绑定到IEnumerable <T>,并在XAML标记中定义一个ItemTemplate,该模板定义每个T类型的对象的外观:

WPF ListBox using ItemsSource and ItemTemplate 使用ItemsSource和ItemTemplate的WPF ListBox

<ListBox x:Name="listBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" Foreground="Green" FontSize="16" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM