Tuesday, 11 May 2010

Silverlight 4 – Drop target example

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

    1. <Grid x:Name=”LayoutRoot” Background=”White”>
    2.        <TextBlock Height=”229” HorizontalAlignment=”Left” Margin=”64,27,0,0” Name=”textBlock1” VerticalAlignment=”Top” Width=”266′” AllowDrop=”True” Drop=”textBlock1_drop” />
    3. </Grid>

4. Now in the code behind, we need to add the textBlock1_drop method. (If the method is already there change the body)

    1. private void textBlock1_drop(object sender, DragEventArgs e)
    2. {
    3.      FileInfo[] dropFileInfo = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
    4.      if (dropFileInfo.Count() > 0)
    5.      {
    6.            StringBuilder fileContent = new StringBuilder();
    7.            using (StreamReader dropFileStream = fi[0].OpenText())
    8.                   fileContent.Append(dropFileStream.ReadToEnd());
    9.            textBlock1.Text = fileContent.toString();
    10.      }
    11. }

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.


Post a Comment