Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Drag & Drop Gridview in C#

0.00/5 (No votes)
4 Aug 2014 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

<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

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"

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

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

 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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here