Silverlight working as a drop target

by Lord Cod3n 1. December 2009 10:25

The best example I was able to ponder through involved windows explorer and dropping files from explorer to your Silverlight OOB application.  So along this note lets see what we have to do to make this work.  As a slight change of pace I will be doing the demo in Blend.

I thought I would show this feature of Blend 4 Preview.  Notice the Silverlight Project Options so you can create an OOB application inside of Blend.

image

This is not needed but I thought it would be beneficial to go through this process.  So first we set our application to be an OOB.  Here is a pop up you get when you run the application for the first time.  You need to install it before you can run it OOB.

image

Next add an image control, Name it imgDisplay.  This will be the display the image from the drag and drop.

image

You need to check AllowDrop for LayoutRoot.

image

Interesting effect here that I found the imgDisplay also has it's AllowDrop set because the parent is set.

image

Next we need to enable the drop event for LayoutRoot.  Clicking on the event icon will get you a list of events.

image

Double Click the Drop Handler.  It will auto create the event and wire it up.  Here is the code for the drop handler.

private void LayoutRoot_Drop(object sender, System.Windows.DragEventArgs e){   
if(e.Data!=null)   
 {        
	IDataObject dataobj = e.Data as IDataObject;        
	FileInfo[] i = dataobj.GetData(DataFormats.FileDrop) as FileInfo[];        
	using (var stream = i[0].OpenRead())            {               
		 var source = new BitmapImage();
	                source.SetSource(stream); 
	               imgDisplay.Source=source;            
		}        
	}    
	}
}

 

The first line verifies  that we have drop data to work with.  We then convert the data to the IDataObject Interface.  We get a list of FileInfo objects back as the data from our drop target.  We take the first drop item and set the source value for our imgDisplay container. The results returned are an array of FileInfo objects so you can work with multiple images and other files if you need to.

Here is screen shot of before and after OOB drop target:

image

image

image

 

 

Here is the source code for the project I hope you find it helpful.   I initially wanted to use a ListBox but ran into some issues so keep yours eyes posted I will be doing a follow up. 

Here is the source code

DropTarget.rar (137.10 kb)

Code Happy,

Bill Moore

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

About the author

William Moore is the lead Software Architect and Technologist for Coden Enterprises. He has more than a decade of software development experience primarily Microsoft Platforms.  William enjoys the full gamit of coding everything from the UI down to the database.

Most comments

Page List