wpf DragDrop FileList
wpf DragDrop
ポイント 1. Window でAllowSrop=“True” 2. PreviewDragOverとDropイベント使用
Window x:Class="DragFromExplorerSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:my="clr-namespace:DragFromExplorerSample" Title="MainWindow" Height="350" Width="525" AllowDrop="True" Drop="Window_Drop" PreviewDragOver="Window_PreviewDragOver"> <Window.DataContext> <my:MyFileList /> </Window.DataContext> <Grid> <ListBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding FileNames}" /> </Grid> </Window>
using System.Collections.ObjectModel; using System.Windows; namespace DragFromExplorerSample { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Drop(object sender, DragEventArgs e) { MyFileList list = this.DataContext as MyFileList; string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; if (files != null) { foreach (var s in files) list.FileNames.Add(s); } } private void Window_PreviewDragOver(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, true)) e.Effects = DragDropEffects.Copy; else e.Effects = DragDropEffects.None; e.Handled = true; } } public class MyFileList { public MyFileList() { FileNames = new ObservableCollection<string>(); } public ObservableCollection<string> FileNames { get; private set; } } }