Have you ever wanted to give the user the ability to drag a file from you desktop or file explorer onto your Silverlight application? Well, up until now you couldn’t. What’s that sound? It’s a bird… it’s a plane… no, it’s Silverlight 4 Beta. Yes, Silverlight 4 Beta is coming to the rescue and giving you the ability to have your Silverlight application act as a drop target. And it is so easy to do. Observe.
First just identify the UI element you want to use as the drop target, then set the AllowDrop property to true. Then just handle the Drop events.
Here is a quick example. This examples allows a user to drag a bitmap from their file system into my application and displays the images in a ScrollViewer. Here is the XAML
<StackPanel x:Name="LayoutRoot" Background="White">
<TextBlock Text="Drop image below." FontSize="16" FontWeight="BOld" HorizontalAlignment="Center" />
<ScrollViewer x:Name="ImagesTarget" Background="White" Width="800" MinHeight="300"
VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Auto" AllowDrop="True">
<ItemsControl x:Name="ImageList">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}" Margin="5" Stretch="UniformToFill" Height="240" />
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</ScrollViewer>
</StackPanel>
I create a ObservableCollection of bitmap images and use this as the ItemsSource for the ScrollViewer.
ObservableCollection<BitmapImage> _images = new ObservableCollection<BitmapImage>();
I hook into the Drop event in the load event of the form.
ImagesTarget.Drop += new DragEventHandler(ImagesTarget_Drop);
Now lets implement the Drop event to loop through all the files and add them to the list.
void ImagesTarget_Drop(object sender, DragEventArgs e)
{
if (e.Data == null)
return;
IDataObject dataObject = e.Data as IDataObject;
FileInfo[] files =
dataObject.GetData(DataFormats.FileDrop) as FileInfo[];
foreach (FileInfo file in files)
{
try
{
using (var stream = file.OpenRead())
{
var imageSource = new BitmapImage();
imageSource.SetSource(stream);
_images.Add(imageSource);
}
}
catch (Exception)
{
MessageBox.Show("Not a suppoted image.");
}
}
}
Bingo… Bango… Boom, that is all there is to it. And of course, you can handle the other drag events to have more control over what is being dropped and where.