Drag and Drop in Silverlight 4 DataGrid

Drag and Drop achieves using the DataGridDragDropTarget which is located in Silverlight Toolkit. We need to write a bit code in .cs file to catch the data. In order to get the required thing we must enclose both or any no of grids, inside DataGridDragDropTarget  tags.
I completed this functionality by binding my both grids to ObservableCollection<> of same class type, Employee.

1. Add Reference:

In your silverlight project, add reference of this:
System.Windows.Controls.Data.Toolkit

In Your xaml file, add this reference:

xmlns:toolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Toolkit"

2. Writing Xaml:

Enclose your grid on which you wanted to have Drag and Drop feature in DataGridDragDropTarget tag like below:

<toolkit:DataGridDragDropTarget AllowDrop="True"
                                        AllowedSourceEffects="Copy"
                                        HorizontalAlignment="Left"
                                        VerticalAlignment="Top"
                                        Margin="10, 10, 0, 0"
                                        ItemDragCompleted="DataGridDragDropTarget_ItemDragCompleted" >
            <sdk:DataGrid AutoGenerateColumns="False"
                          Height="150"
                          HorizontalAlignment="Left"
                          Name="FirstGrid"
                          VerticalAlignment="Top"
                          Width="376"
                          ColumnWidth="*"
                          SelectionMode="Extended"
                          ItemsSource="{Binding}">
                 <sdk:DataGrid.Columns>
                    <sdk:DataGridTextColumn Binding="{Binding FirstName}"
                                            Header="FirstName" />
                    <sdk:DataGridTextColumn Binding="{Binding LastName}"
                                            Header="LastName" />
                </sdk:DataGrid.Columns>

          </sdk:DataGrid>
   </toolkit:DataGridDragDropTarget>

AllowedSourceEffects   => you can choose to cut or copy the row, i choose copy
DataGridDragDropTarget_ItemDragCompleted   => this event fires when drag operation is completed,  remember one thing that is, this event should be attached with that grid from the element is being dragged, not on that grid where you place you element.

Class of Employee:

public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }

    }

3. Write Code Behind:

In this step we write the code required in .cs file.

Populating the collection:

As i am using 2 grids, i am populating different collection for each.

         /// <summary>
        /// populate employee collection
        /// </summary>
        /// <returns></returns>

        public ObservableCollection<Employee> LoadEmployee ()
        {
            ocEmployee = new ObservableCollection<Employee>();
            ocEmployee.Clear();
            ocChild = LoadChilds();

            ocEmployee.Add(new Employee() { FirstName = "asdf", LastName = "hjkl" });
            ocEmployee.Add(new Employee() { FirstName = "qwer", LastName = "uiop" });
            ocEmployee.Add(new Employee() { FirstName = "zxcv", LastName = "m,./" });

            return ocEmployee;
        }

ocEmployee  => public ObservableCollection<Employee> ocEmployee; declared at class level

/// <summary>
/// populating more employee collection
/// </summary>
/// <returns></returns>
public ObservableCollection<Employee> LoadMoreEmployee ()
{
    ocMoreEmployee = new ObservableCollection<Employee>();
    ocMoreEmployee.Clear();
    ocChild = LoadChilds();

    ocMoreEmployee.Add(new Employee() { FirstName = "bat", LastName = "man" });
    ocMoreEmployee.Add(new Employee() { FirstName = "wonder", LastName = "women"});
    ocMoreEmployee.Add(new Employee() { FirstName = "bruce", LastName = "lee"});

    return ocMoreEmployee;
}

Main Event:

        /// <summary>
        /// when drag is completed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGridDragDropTarget_ItemDragCompleted (object sender, ItemDragEventArgs e)
        {           
            SelectionCollection secCol = e.Data as SelectionCollection;
         
            if (SecondGridDrag)
            {
                Employee emp = (Employee) FirstGrid.SelectedItem;
                    for (int i =0; i < secCol.Count; i++)
                    {
                        ocEmployee.Insert(index,secCol[i].Item as Employee);
                    }
            }

            else
            {
                Employee emp = (Employee) SecondGrid.SelectedItem;
                    for (int i =0; i < secCol.Count; i++)
                    {
                        ocMoreEmployee.Add(secCol[i].Item as Employee);
                    }
            }

            FirstGridDrag = false;
            SecondGridDrag = false;
        }

FirstGridDrag, SecondGridDrag     => bool variable, i created to check which grid is doing the drag operation.

Do favour me with your suggestions!

Popular Posts