#708 – 将文件拖入到WPF应用程序中(Dragging a File Into a WPF Application)

来源:互联网 发布:怎么添加usb端口 编辑:程序博客网 时间:2024/06/12 11:04

原文地址:https://wpf.2000things.com/2012/12/10/708-dragging-a-file-into-a-wpf-application/

如果你的应用程序中允许将文件拖入,那么就需要使用DataFormats.FileDrop 类型的数据。

在代码中指定只允许FileDrop 类型的数据进入。

private void Window_DragEnter(object sender, DragEventArgs e){    if (e.Data.GetDataPresent(DataFormats.FileDrop))        e.Effects = DragDropEffects.Copy;    else        e.Effects = DragDropEffects.None;     e.Handled = true;} private void Window_DragOver(object sender, DragEventArgs e){    if (e.Data.GetDataPresent(DataFormats.FileDrop))        e.Effects = DragDropEffects.Copy;    else        e.Effects = DragDropEffects.None;     e.Handled = true;}

当你在Drop 事件处理函数中调用GetData 函数的时候,你会获得被拖入文件的文件名数组。下面是一个列子,在Label 上显示拖入文件的文件名并且用TextBlock 显示文件中的文本内容。

private void Window_Drop(object sender, DragEventArgs e){    string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);     lblFilename.Content = filenames[0];     txtContent.Text = File.ReadAllText(filenames[0]);}

708-001

708-002



0 0
原创粉丝点击