How to drag and drop local files to Silverlight application

This sample you can find it in All-In-One code framework. Somehow you will not see margin in between each picture. I have done a small modification to do that as the code below.

// Handle drop event here. private void LayoutRoot_Drop(object sender, DragEventArgs e)
    if (e.Data != null)
        // Get fileinfos. var files = e.Data.GetData(DataFormats.FileDrop) as FileInfo[];

        foreach (var file in files)
            var image = new Image();
                try {
                    // Read file stream. var stream = file.OpenRead();
                    var bitmapimage = new BitmapImage();
                    image.Source = bitmapimage;
                catch {
                    // If read failed, use default icon . image.Source = new BitmapImage(new Uri("/images/file.png", UriKind.Relative));
            else // If not image type file, use default icon image. image.Source = new BitmapImage(new Uri("/images/file.png", UriKind.Relative));

            image.DataContext = file;
            image.Height = cellsize - 10;
            image.Width = cellsize - 10;

            var positon = e.GetPosition(LayoutRoot);
            Canvas.SetLeft(image, positon.X);
            Canvas.SetTop(image, positon.Y);

            // Init icon drag&drop behavior InitIconDragDrop(image);

            // Snap to grid FlyToGrid(image, itemindex);


// Determine if is silverlight supported image format bool IsImage(string extension)
    extension = extension.ToLower();
    if (extension == ".jpg" ||
        extension== ".jpeg" ||
        extension == ".png")
        return true;
    else return false;

int cellsize = 100;
  // Snap to grid animation void FlyToGrid(UIElement element,int index)
            int cellcolcount = (int)LayoutRoot.ActualWidth/cellsize;
            int row = index / cellcolcount;
            int col = index % cellcolcount;

            int endposx = col * cellsize;
            int endposy = row * cellsize;

            Storyboard sb = new Storyboard();

            DoubleAnimation dax = new DoubleAnimation();
            Storyboard.SetTarget(dax, element);
            Storyboard.SetTargetProperty(dax, new PropertyPath(Canvas.LeftProperty));
            dax.To = endposx;
            dax.Duration = new Duration(TimeSpan.FromSeconds(0.5));
            dax.EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut };

            DoubleAnimation day = new DoubleAnimation();
            Storyboard.SetTarget(day, element);
            Storyboard.SetTargetProperty(day, new PropertyPath(Canvas.TopProperty));
            day.To = endposy;
            day.Duration = new Duration(TimeSpan.FromSeconds(0.5));
            day.EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut };


        bool isdrag = false;
        Point relativepos;

        // Initialize element drag&drop behavior void InitIconDragDrop(UIElement element)
            element.MouseLeftButtonDown += (s, e) =>
                    isdrag = true;
                    relativepos = e.GetPosition(element);

            element.MouseLeftButtonUp += (s, e) =>
                    var pos = e.GetPosition(LayoutRoot);
                    var colcount = (int)LayoutRoot.ActualWidth / cellsize;
                    var col = Math.Max(0, Math.Min((int)pos.X / cellsize, colcount - 1));
                    var rowcount = (int)LayoutRoot.ActualHeight/cellsize;
                    var row = Math.Max(0, Math.Min((int)pos.Y / cellsize, rowcount - 1));

                    var index = row * colcount + col;

                    FlyToGrid(element, index);

                    isdrag = false;

            element.MouseMove += (s, e) =>
                    if (isdrag)
                        var pos = e.GetPosition(LayoutRoot);
                        Canvas.SetLeft(element, pos.X - relativepos.X);
                        Canvas.SetTop(element, pos.Y - relativepos.Y);

About chanmingman

Since March 2011 Microsoft Live Spaces migrated to Wordpress ( till now, I have is over 1 million viewers. This blog is about more than 50% telling you how to resolve error messages, especial for Microsoft products. The blog also has a lot of guidance teaching you how to get stated certain Microsoft technologies. The blog also uses as a help to keep my memory. The blog is never meant to give people consulting services or silver bullet solutions. It is a contribution to the community. Thanks for your support over the years. Ming Man is Microsoft MVP since year 2006. He is a software development manager for a multinational company. With 25 years of experience in the IT field, he has developed system using Clipper, COBOL, VB5, VB6, VB.NET, Java and C #. He has been using Visual Studio (.NET) since the Beta back in year 2000. He and the team have developed many projects using .NET platform such as SCM, and HR based applications. He is familiar with the N-Tier design of business application and is also an expert with database experience in MS SQL, Oracle and AS 400.
This entry was posted in .Net and tagged . Bookmark the permalink.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.