Silverlight 4.0 Tutorial: Drag-n-drop External Files

Introduction

As the title points out this article would be a tutorial for the drag drop files feature in Silverlight. This drag drop feature is introduced in Silverlight 4.0. Silverlight 4.0 can be downloaded here.

In this article I will create a sample Silverlight application and implement the drag drop files feature. The sample application will be developed using Silverlight 4.0 and Microsoft Visual Studio 2010.

Drag-n-drop External Files in Silverlight - An Overview

In Silverlight 4.0 with the introduction of the drag drop external files feature the user can just drag the file from his local system and drop it onto the designated Silverlight controls on the Silverlight application. Below are some advantages that this feature exhibits.

  • This feature definitely provides a rich user experience.
  • The drag drop can be implemented on any Silverlight control on the Silverlight application.
  • Multiple files can be dropped on the Silverlight control at the same time.

If you are a normal ASP.NET developer then you would definitely realize the power of the feature where the users can drag and drop the files onto the browser window.

AllowDrop Attribute and Drop Event of Silverlight Controls

In order for a Silverlight control to support dropping files on them AllowDrop attribute should be set to True. The Drop event will be raised when the files are dropped on the Silverlight control. This Drop event is supported by all the Silverlight controls. Note that even if the Drop event is defined for the control but if the AllowDrop is set to False then the drag drop files will not work. Below is a sample XAML code where a TextBlock is having a Drop event defined.

  <Grid x:Name="LayoutRoot" Background="White">
          <TextBlock AllowDrop="True" Drop="TextBlock_Drop" Height="100" Width="200" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold" TextAlignment="Center" Text="Drop your files here...">
          </TextBlock>
  </Grid>

Below mentioned are few more events linked to the Drag Drop functionality.

  1. DragEnter - Fires when the dragged files enter the control.
  2. DragLeave - Fires when the dragged files leave the control.
  3. DragOver - Fires when the dragged files move over the control.

Reading the Dropped Files in C# Programming

The dropped files over the Silverlight control can be read inside the Drop event handler implementation in the code behind. Object sender and DragEventArgs object are the parameters of the Drop event handler as shown below.

  private void TextBlock_Drop(object sender, DragEventArgs e)
  {
  
  }

In order to get the context of the dropped files the DragEventArgs object has to be used and the file can be read into a FileStream. The file stream can be used to perform either a save operation onto the server or any other binding operations can be performed. Below is the sample code:

  private void TextBlock_Drop(object sender, DragEventArgs e)
  {
       //Get the FileInfo of the list of dropped files into a FileInfro array
       FileInfo[] fileArray = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
  
       foreach (var fileInfo in fileArray)
       {
            using (FileStream fileStream = fileInfo.OpenRead())
            {
                      //use the fileStream object to perform the required operation
            }
       }
  }

Note that my comments are in-lined in the above code.

Sample Application Implementing Drag-n-drop Feature in Silverlight

Let us go ahead and create a sample Silverlight application implementing the drag drop files feature. The application would do the following:

  • Allows drag dropping a set of files onto a Silverlight control
  • If the dropped file is text file content will be populated in a TextBlock.
  • If the dropped file is a .jpg file then populate the image in an Image control.

Create a Silverlight application and name it as DragDropFilesDemo along with a hosting web application named DragDropFilesDemo.Web. In the Silverlight client project open MainPage.XAML designer. This is where you need to define the Silverlight client UI using XAML. Below is the XAML code for the sample drag drop application XAML UI.

  <UserControl x:Class="DragDropFilesDemo.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      d:DesignHeight="500" d:DesignWidth="600">
  
      <Grid>
          <Canvas Background="Beige" AllowDrop="True" Name="DragDropCanvas" Drop="DragDropCanvas_Drop" DragEnter="DragDropCanvas_DragEnter" DragLeave="DragDropCanvas_DragLeave" Height="100" Width="600" HorizontalAlignment="Center" VerticalAlignment="Top" >
              <TextBlock Name="DragDroptextBlock" Text="Drop your files here...">
              </TextBlock>
          </Canvas>
          <StackPanel x:Name="TextPanel" HorizontalAlignment="Left" VerticalAlignment="Bottom" Height="400" Width="300" ></StackPanel>
          <StackPanel x:Name="ImagePanel"  HorizontalAlignment="Right" VerticalAlignment="Bottom" Height="400" Width="300" ></StackPanel>
      </Grid>
  </UserControl>

As you could see in the above XAML the DragDropCanvas Panel is the container which would allow the user to drag drop the files. The additional settings related to Drag Drop functionality which are done to the canvas panel are below:

  • a. AllowDrop="True"
  • b. Drop event
  • c. DragEnter event
  • d. DragLeave event

It is not necessary to have the DragEnter and DragLeave events but in our sample application I wanted to have the text "Drop you files here..." to be shown in bold while the files are dragged into the canvas by the user.

StackPanels with ids TextPanel and ImagePanel are the containers to hold the TextBlock and Image control which will be added dynamically.

Now go ahead and implement the code behind for achieving the drag drop functionality. Below is the C# programming code for MainPage.XAML.cs file.

  namespace DragDropFilesDemo
  {
      public partial class MainPage : UserControl
      {
          public MainPage()
          {
              InitializeComponent();
          }
  
          private void DragDropCanvas_Drop(object sender, DragEventArgs e)
          {
              //Get the FileInfo of the list of dropped files into a FileInfro array
              FileInfo[] fileArray = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];
  
              foreach (var fileInfo in fileArray)
              {
                  using (FileStream fileStream = fileInfo.OpenRead())
                  {
                      if (fileInfo.Extension.ToUpper().Equals(".JPG"))
                          AddImage(fileStream);
                      else if (fileInfo.Extension.ToUpper().Equals(".TXT"))
                          AddTextBlock(fileStream);
                  }
              }
  
              //Set the font weight back to normal
              DragDroptextBlock.FontWeight = FontWeights.Normal;
          }
  
          private void AddTextBlock(FileStream fileStream)
          {
              using (StreamReader reader = new StreamReader(fileStream))
              {
                  TextBlock textBlock = new TextBlock()
                  {
                      Width = 200,
                      Text = reader.ReadToEnd(),
  			Margin = new Thickness(2.0)
                  };
  
                  TextPanel.Children.Add(textBlock);
              }
          }
  
          private void AddImage(FileStream fileStream)
          {
              BitmapImage bitMapImage = new BitmapImage();
              bitMapImage.SetSource(fileStream);
              Image image = new Image()
              {
                  Source = bitMapImage,
                  Width = 25,
                  Height = 25,
                  Margin = new Thickness(2.0)
              };
  
              ImagePanel.Children.Add(image);
          }
  
          private void DragDropCanvas_DragEnter(object sender, DragEventArgs e)
          {
              //Set the font weight to bold
              DragDroptextBlock.FontWeight = FontWeights.Bold;
          }
  
          private void DragDropCanvas_DragLeave(object sender, DragEventArgs e)
          {
              //Set the font weight back to normal
              DragDroptextBlock.FontWeight = FontWeights.Normal;
          }
      }
  }

That is it we are done with all the coding for the sample application implementing the new drag drop feature of Silverlight 4.0. Run the application, drag drop a set of .TXT and .JPG files onto the CanvasPanel area and witness that the text file content are displayed in the TextBlocks / the .JPG files are displayed as Images on the page.

Conclusion

Hope this article explains the drag drop external files feature of Silverlight 4.0 extensively. Go through the sample code for implementing drag drop functionality in Silverlight 4.0 which is provided in this article. Please let me know if you have any doubts or need any further clarifications. Happy Reading!



About the Author

V.N.S Arun

I work for an MNC in Bangalore, India. I am fond of writing articles, posting answers in forums and submitting tips in dotnet. To contact me please feel free to make use of the "Send Email" option next to the display name.

Comments

  • No titles!

    Posted by Caroline on 11/25/2013 08:47am

    Thanks! A good, complete overview.

    Reply
  • Analyst

    Posted by John Preston on 04/23/2012 09:25pm

    Great example, I was wondering if you can bind the image you drop on the canvass? I have created an image type field in a SQL database and want to save the image that dropped to the database using RIA services.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date