Ok, Silverlight 4 is here and everyone's very happy and excited (well.. I think it's just more fun now to use Silverlight - especially with the nice toolkit, which can be found on codeplex). Yesterday I tried one of the new features and wow, it was pretty easy to implement drag and drop for Silverlight 4 applications.
So let's say you got a Listbox, like the following one
<ListBox x:Name="myListBox" />
Now you have to add e few things:
- Allow Drop with AllowTrop="True"
- An eventhandler for the Drop event
- And finally if you want eventhandlers for DragEnter and DragLeave
The whole thing should look like the following
<ListBox Name="myListBox"
AllowDrop="True"
Drop="myListBox_Drop"
DragEnter="myListBox_DragEnter"
DragLeave="myListBox_DragLeave" />
Lets talk about the "Drop" event for a moment. Drop supplies the event handler with the arguments from DragEventArgs: Take a look at it on
MSDN. Here's how I handle the event
private void myListBox_Drop(object sender, DragEventArgs e)
{
FileInfo[] droppedFiles = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
for (int i = 0; i < droppedFiles.Length; i++)
{
this.myListBox.Items.Add(droppedFiles[i].Name);
/* you have to access the data in the listbox via droppedFiles[i].OpenRead()
things like File.OpenRead(droppedFiles[i].FullName) won't work because
of the Silverlight 4 security model */
}
e.Handled = true;
}
Additionally you can use the DragEnter and DragLeave event to alert the user, that dragged files can be dropped on the object - just change the background colour or something like that (a border is quite nice as well).