Friday 1 June 2012

Drag and Drop in silverlight 4


 In this article i'm  going to explain  how to create a  drag   drop  effect   on  a   control  in  silverlight 4
  •         first  create  the  control  that  you  want  to apply  the  drag  drop  effect  to.

  •         Then  we   are   goint   to use   three  events  on  the control  1) MouseLeftButtonDown 2) MouseLeftButtonUp 3) MouseMove

  •          In   the   MouseLeftButtonDown   we  are  going to  set  a flag  to  indicate  if   mouse  left button  is in pressed  position  and  also   get   the  x  and   y   position   of  the   Control

  •          When   the  MouseMove  event  occurs  while  MouseLeftButton is in pressed position,we can  set   the  margin  of  the  control   ,as   according  to  the   previous   x,y   position   of  the  control


      In   the   below   example    i  have   used   a    grid   to   demonstrate   drag    and   drop.


  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace DD
{
    public partial class MainPage : UserControl
    {
        bool dragdropineffect,dragdropineffect2;
        double a, b,c,d,a1,b1,pos;

        public MainPage()
        {
            InitializeComponent();
                  
        }
      
        private void grid1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement fe = sender as FrameworkElement;
            fe.CaptureMouse();
            dragdropineffect = true;

            a1 = e.GetPosition(LayoutRoot).X - grid1.Margin.Left;
            b1 = e.GetPosition(LayoutRoot).Y - grid1.Margin.Top;
        }

        private void grid1_MouseMove(object sender, MouseEventArgs e)
        {
            if (dragdropineffect == true)
            {
                //grid1.Cursor = Cursors.Hand;
                a = e.GetPosition(LayoutRoot).X - a1;
                
                b = e.GetPosition(LayoutRoot).Y - b1;
                grid1.Margin = new Thickness(a, b, 0, 0);
            }
        }

        private void grid1_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            dragdropineffect = false;
            
        }
    }
}


No comments:

Post a Comment