Click here to Skip to main content
15,881,172 members
Articles / Desktop Programming / XAML
Tip/Trick

Drag & Drop Gridview in C#

Rate me:
Please Sign up or sign in to vote.
4.92/5 (4 votes)
4 Aug 2014CPOL 23.7K   3   9   1
This sample is based on Drag and Drop between GridView

Introduction

Sometimes, we need to implement Drag&Drop in our project and there are many different methods to do that. My method is more advanced and it can help you detect the item dropped between GridViews. So I prepared an exercise to explain.

You can download this sample here.

Background

The concept of the exercise is to drop the Animal's name on his correct picture so we must know which item of Gridview we dropped on.

Using the Code

The key of doing this concept is based on using User Control on creating the GridView.

1. Add the User Control "DropTargetUserControl"

DropTargetUserControl.xaml

XML
<UserControl
    x:Class="Drag_and_Drop_GridView.DropTargetUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Drag_and_Drop_GridView"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
   d:DesignHeight="300"
    d:DesignWidth="180" 
    AllowDrop="True" 
    Drop="DropUserControl_Drop" 
    DragEnter="DropUserControl_DragEnter" 
    DragLeave="DropUserControl_DragLeave">

    <Grid Width="180" Height="300" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="2*"/>
        </Grid.RowDefinitions>
        <Grid Background="White"
              Visibility="Collapsed"  
              Name="gridtop">
            <TextBlock Text="" 
                       VerticalAlignment="Center" 
                       Name="correct" 
                       Visibility="Collapsed" 
                       Foreground="Black" 
                       HorizontalAlignment="Center" 
                       FontSize="20"/>
        </Grid>

        <MediaElement Name="question" 
                      AutoPlay="True" 
                      Source=""/>
        <Image x:Name="ImageItem" 
               Stretch="Fill" 
               Grid.Row="1"/>
        <Border  x:Name="BorderHighlight" 
                 BorderBrush="#FF0083FF"
                 BorderThickness="5" 
                 Visibility="Collapsed"  
                 Grid.RowSpan="2"/>

    </Grid>
</UserControl>

The important three Events in this User Control are Drop (when we finish drop), DropEnter (when we focus with dropping), DropLeave (when we lose focus on dropping).

DropTargetUserControl.xaml.cs

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace Drag_and_Drop_GridView
{
    public sealed partial class DropTargetUserControl : UserControl
    {
        string correctAnswer, img, audios;

        public DropTargetUserControl(string itemName, string Image)
        {
            this.InitializeComponent();
            correctAnswer = itemName;
            correct.Text = itemName;
            img = Image;
            ImageItem.Source = new BitmapImage(new Uri("ms-appx:///" + img, UriKind.RelativeOrAbsolute));
        }

        async private void DropUserControl_Drop(object sender, DragEventArgs e)
        {
            BorderHighlight.Visibility = Visibility.Collapsed;

            string data = await e.Data.GetView().GetTextAsync();

            //compare the dragged item with the dropped one
            if (data == correctAnswer)
            {
                Statique._mainViewModel.SwitchItem(data);
                correct.Visibility = Windows.UI.Xaml.Visibility.Visible;
                gridtop.Visibility = Windows.UI.Xaml.Visibility.Visible;
            }
        }

        private void DropUserControl_DragEnter(object sender, DragEventArgs e)
        {
            BorderHighlight.Visibility = Visibility.Visible;  
        }

        private void DropUserControl_DragLeave(object sender, DragEventArgs e)
        {
            BorderHighlight.Visibility = Visibility.Collapsed;

        }
    }
}

I used to use XML to load my static information, so I will show you how to load it and wrap it with a List.

2. Add a Class named "TextImage"

C#
public class TextImage
  {
      public string Texts { get; set; }
      public string Images { get; set; }
  }

On the Mainpage.xaml.cs, add the function "Parse":

C#
private const string FilesPath = "Matching.xml";
        public void Parse()
       {
            //Load Information from Xml file
           XDocument loadedData = XDocument.Load(xmlPath);

           List<DropTargetUserControl> listdrop = new List<DropTargetUserControl>();
           var data = loadedData.Descendants("matching").ToList();

           ObservableCollection<TextImage> listetextimage = new ObservableCollection<TextImage>();
           foreach (var item in data)
           {
                   listetextimage.Add(new TextImage() {
                       Texts = (string)item.Attribute("Text"),
                       Images = (string)item.Attribute("Image"),
                   });
           }

           //Add items
           Statique._mainViewModel.InsertList(listetextimage);
           foreach (var item in listetextimage)
           {
               listdrop.Add(new DropTargetUserControl(item.Texts,item.Images));
           }
           listdrop = (List<DropTargetUserControl>) Statique.Shuffle(listdrop);

            //Binding List with GridView
           GridViewMain2.ItemsSource = listdrop;
       }

With this sample, you can create many Education Apps especially for children based on drag and drop.

Image 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Junior) Microsoft Student Partners
Tunisia Tunisia
I study Software Engineering , 23 years old , I'm motivated with all Technologies of Microsoft.
Since I have been in the Community of Microsoft as Microsoft Student Partners, I developped many apps on the platform Windows and Phone. Now , it's time to share what I learn here and I'am ready to help Everyone.
You can contact me at any time (anisderbel@outlook.com)
This is a Organisation

9 members

Comments and Discussions

 
GeneralMy vote of 4 Pin
vutamdung25-Aug-14 22:00
vutamdung25-Aug-14 22:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.