Sharker Khaleed Mahmud Silverlight Tips & Tricks

September 16, 2010

89. File Drag-and-Drop Support in Silverlight

Filed under: Silverlight — Tags: , , — Sharker Khaleed Mahmud | shamrat231 @ 10:22 AM

[tweetmeme source=”shamrat231” only_single=false]

In this entry, I will talk about drop support that came with Silverlight 4. It is actually very simple to use and you can take the advantage of it if you happen to create a simple Silverlight Image Editor. This is a simple introduction to an editor currently I am working to customize images and in future apply adobe effects. However, in this entry, I will talk about only image(s) drag and drop from external place to your Silverlight application.

You can see the live example here [live demo]   

The SOURCE CODE(.zip) is at the end of the page for download.

First I will start coding drag feature. An image at the moment can easily be dragged using the default MouseDragElementBehavior. So just add that to your image and it will become draggable as shown in the code below.

MainPage.xaml

    <Grid x:Name=”LayoutRoot” Background=”Black”>
        <Image x:Name=”DropImage” Width=”400″ Cursor=”Hand”>
            <i:Interaction.Behaviors>
                <ei:MouseDragElementBehavior ConstrainToParentBounds=”True”/>
            </i:Interaction.Behaviors>
        </Image>
    </Grid>

Silverlight is too fun, when coding gets this simple :). So the image can now be dragged around. Now lets add the drop feature.

For making everything very simple, I will just now add AllowDrop=”True” and then add a drop handler to handle any file that is being dropped.

Now, lets move to the code behind. For demonstration purpose, I will use images from deviantArt gallery.

MainPage.xaml.cs

        //make sure you drag an image to drop
        private void LayoutRoot_Drop(object sender, DragEventArgs e)
        {
            if (e.Data != null)
            {

            }
        }

Now reading a drop file, this can be easily be done as shown below. You can drop multiple files in the editor, but in this scenario I will code to get only one file.

                //reading the drop file
                FileInfo file = ((FileInfo[])e.Data.GetData(DataFormats.FileDrop)).FirstOrDefault();

Now, we have actually got hold of the file that is being dropped. At the moment, I have assumed that the file drop is an image. If it is not then you should implement code to handle that kind of scenario. I will not talk about that but go ahead and assuming the user did drop an image file.

So we now have a reference to the dropped file. Lets create BitmapImage of the dropped file.

                //creating a bitmapImage
                BitmapImage img = new BitmapImage();
               
                using (Stream s = file.OpenRead())
                {
                    img.SetSource(s);
                }

Once that is done, set the image to your image control in xaml like this.

                //setting the image in xaml
                DropImage.Source = img;

You are done applying the above image. Now lets save the collection of drop image.

        <StackPanel x:Name=”DropCollection” Height=”100″ Margin=”10,30,10,10″ VerticalAlignment=”Top” HorizontalAlignment=”Center” Orientation=”Horizontal”>
        </StackPanel>

Everytime a image is dropped, I will add it to my Stackpanel. You can add scrollviewer or use ItemsControl to hold the collection. I will be using stackpanel for demonstration purpose.

        //make sure you drag an image to drop
        private void LayoutRoot_Drop(object sender, DragEventArgs e)
        {
            if (e.Data != null)
            {
                //reading the drop file
                FileInfo file = ((FileInfo[])e.Data.GetData(DataFormats.FileDrop)).FirstOrDefault();

                //creating a bitmapImage
                BitmapImage img = new BitmapImage();
               
                using (Stream s = file.OpenRead())
                {
                    img.SetSource(s);
                }

                //setting the image in xaml
                DropImage.Source = img;

                Image newImage = new Image { Source = img };
                newImage.MouseLeftButtonDown += (a, b) =>
                {
                    DropImage.Source = newImage.Source;
                };

                DropCollection.Children.Add(newImage);
            }
        }

As you can see, that dropped image is added to the collection. Click on the collection image and that will be displayed on the center image. This sample can easily be updated allowing multiple Images to be dragged and dropped but I will continue with it on my next entry.

As always, you can download the source code from here [download link]

Sharker Khaleed Mahmud
Web Developer

Advertisements

10 Comments »

  1. Nice topic. I got an issue about drag-and-drop. It doesn’t support ChildWindow in silverlight. Have you ever met this issue?

    Comment by Kevin — September 16, 2010 @ 5:26 PM

  2. Nice work you got the code down as small as I have ever seen it. Makes the way I was doing it only 4 months ago look old fashioned 🙂

    Comment by Michael Washington — September 17, 2010 @ 12:24 PM

  3. cool. it’s very useful.

    Comment by henry — September 19, 2010 @ 2:27 AM

  4. […] Drag-and-Drop Support in Silverlight (Sharker Khaleed Mahmud) […]

    Pingback by Windows Client Developer Roundup 042 for 9/20/2010 - Pete Brown's 10rem.net — September 20, 2010 @ 6:18 AM

  5. […] заметки: использование буфера обмена (clipboard) и поддержка Drag-And-Drop в […]

    Pingback by Andrey on .NET | Интересности #6 — September 20, 2010 @ 9:28 AM

  6. […] last entry, I talked about drag-and-drop image. In this I will write about how you can draw your image and maybe in next post save it. Today for […]

    Pingback by Drawing on Image in Silverlight « Sharker Khaleed Mahmud Silverlight Tips & Tricks — September 25, 2010 @ 6:26 AM

  7. Nice post ! like it !

    Comment by phamnguyenit — January 10, 2011 @ 4:54 PM

  8. Hi mate, great website, really well illustrated samples with working demo’s, appreciate the work. Your tutorials have helped me a lot

    Comment by red — April 14, 2011 @ 9:02 AM


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: