One of the feature that stand out most in SL4 is drop target other than Print. I am sure most of all of you run into a user story where the user need to drag and drop a file over some web control. Well I will not blame user, since Win XP, most of the desktop application let user do that, so why not the web application do it.
I got some time yesterday night and gave it a try. It turned out to be so easier than I thought it would be.
The objective of my test was to drop a text file over to a text block and display the content in the text block. Very simple. Here are the things I did. Remember this will work only in Silver light 4.
1. Create a silverlight application in VS2010.
2. Open the designer and drop a text block on to the grid control.
3. In the MainPage.xaml, add ‘AllowDrop’ and ‘Drop’ attributes to TextBlock so the modified one will look like this
<Grid x:Name=”LayoutRoot” Background=”White”>
<TextBlock Height=”229” HorizontalAlignment=”Left” Margin=”64,27,0,0” Name=”textBlock1” VerticalAlignment=”Top” Width=”266’” AllowDrop=”True” Drop=”textBlock1_drop” />
4. Now in the code behind, we need to add the textBlock1_drop method. (If the method is already there change the body)
private void textBlock1_drop(object sender, DragEventArgs e)
FileInfo dropFileInfo = e.Data.GetData(DataFormats.FileDrop) as FileInfo;
if (dropFileInfo.Count() > 0)
StringBuilder fileContent = new StringBuilder();
using (StreamReader dropFileStream = fi.OpenText())
textBlock1.Text = fileContent.toString();
That is it, now compile and run it. You will see a web page with content ‘TextBlock’,. Open Windows explorer and drag a text file and drop it over ‘TextBlock’, it should now show you the content of the text file.
Even though We get the file info in drop event, you can not access the file directly from the physical file location, you should only use the file stream to read the content. It is because of the sandbox restriction.