Drag and Drop in WPF using Behavior


Isn't it fun,

to instantly listen to a blog on the go? PLAY !

 
 

WPF-using-Behavior

Drag and drop software improves productivity and user experiences, but some of the application hadoffered drag and drop functionality because they believe it’s really hard. In this blog, we will discuss drag and drop functionality.

DragDropBehaviour is the base class of DragDropsBehaviors. It provides a high-level API to handle the operation of drag and drops functionality. When we control drag and drop functionality it will call automatically.

Table of Content

DragDropBehaviour class is inherited from the other class. So, it can connect with the other classes. You can be drag CandidateViewModel hence it implements an idraggable interface.

The CandidateViewModel can be dropped so it implements an idroppable interface.The ViewModel can be drag and drop so it implements both idragable and idropable.

Behavior Section

Framework behavior starts the drag process. It records the queries for the dragged Data type.When framework behavior is dropped on the framework at the time operation start. It is a subclass of system.window.UIElement class. That we normally see on WPF.

When ListboxBehaviour is dropped on List box at that time operation will perform.

View

Treeview: In Treeview, every element is also a framework element. So in the XAML file in declaration framework behavior and framework element drop behavior are used.

CandidateView: The candidate is candidate framework element, using them we can do drag. The candidate is draping Listbox so for that it uses listboxDropBehaviour class.

The main purpose of dragging is to select the data which transfers it along with defining the data which passed by dragging and it decides the area when the mouse hovers around the screen the informs the system.

iDragabble interface the following:





interface IDragable
    {
        /// Type of the data item
        Type DataType{get;}
        /// Remove the object collection
                void Remove (object i);
    }

Remove method can be used to remove the source data which is a copy operation. Do not simply it. You can add it to your application according to your requirement and improve its performance.

Creating an attached behaviourusing WPF

Basic step to create attached behaviour

  1. Use a public static class.
  2. Add a static dependency property and associated PropertyChangedCallback method.
  3. Add a static method that is static setter and getter.
  4. Add any static method.
  5. Add needed code.


Handling Drag and Drop in WPF

You will need a particular static object if you are handling drag and drop in WPF. This will help you to handle drag and drop.

Predefine data will be in the DataFormat class which will the data which is being dragged and drop. This is used to identify the data. If you are not familiar with the DataObject or iDataObject then you should first understand those concepts by which you can easily call the methods.

If you want to perform drag and drop then you should know which data you have to handle while you are performing drag and drop. You should have information that if selected data is being handled properly or not and what is the type of the selected data. You have an option to handle the behavior of the data behind the code. You can use the PreciewDrop event.

Writing a drop behaviour

  1. Create new class name is DropBehavior.
  2. The class both are public and static.
  3. Add DependencyProperty called PreviewDropCommand Property.
  4. Write the setter and getter method.
  5. Write the Propertycallback method.
DropBehavior.cs
using System.Windows.Input;
using System.Windows;

namespace MVVM
{
    

Using the behavior int the Xaml

Now you can add the data in the grid or the UI Element but cannot perform the drag and drop. If you try to drag and drop in the textbox then it will not work. The event will not be fired.

Example:

Add Dropbehavior to a user control and you can add the DropBehavior to a grid.
 


<usercontrolx: allowdrop="True" class="DropBehaviorExample.ExampleView" d:designheight="300" d:designwidth="400" mc:ignorable="d" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mvvm="clr-namespace:MVVM" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<grid mvvm:dropbehavior.previewdropcommand="{Binding PreviewDropCommand}">
</grid>

</usercontrolx:>

Implementing the ICommand in the ViewModel:

You will need the following code in the ViewModel

public ICommandPreviewDropCommand
{
    get { return _PreviewDropCommand ?? (_PreviewDropCommand = new RelayCommand(HandlePreviewDrop)); }
    set
    {
        _PreviewDropCommand = value;
		NotifyPropertyChanged("PreviewDropCommand");
    }
} 
	private ICommand _PreviewDropCommand;

	The method encapsulated in the relay command
	private void HandlePreviewDrop(object in object)
	{
		IDataObjectido = inObject as IDataObject;
		if (null == ido) return;

		// Get all the possible format
		string [] formats = ido.GetFormats();
 }

Wants to Talk with Our Highly Skilled WPF Developer ?

Your Search ends here.


The goal of the drag and drop operation

  1. It gives you the information that the dragged item can be placed in that particular place or not.
  2. Transfer data to the destination.
  3. Remove data from a source.

Below is iDraggable interface:

interface IDropable
    {
       
 /// Type of the data item ///  Type DataType{ get; } ///  /// Drop data into the collection. ///  ///The data to be dropped ///optional: The index location to insert the data void Drop(object data,double index = -1); }
 

Data type property will define the type of data which helps to put the data in the right place.

You have to do this operation in the view model because it makes it easier to just do drag and drop and you can also add more elements.

The data will be added to the dataset when using the Drop method. As we have seen earlier that data is being added to the Listbox.

You can create a drop method and later you can bound to any mouse event or mouse action. For example, giving background color effects when hovering over the mouse pointer shows a good impression of a programmer. Also changing the thickness of the border of the box by extending or shrinking it or to change the style of the border and by doing many other effects you can show the user that you are dropping your data here(at this place).

As it is shown in the below example.

private void SetDragDropEffects(DragEventArgs e)
        {
			e.Effects = DragDropEffects.None;  //default to None

            if (e.Data.GetDataPresent(dataType))
            {
				e.Effects = DragDropEffects.Move;
            }
        }

And when the data is dropped then also it is necessary to remove the effect which you provided while accepting the data. For this purpose we have developed a program which is as follows :

void AssociatedObject_DragLeave(object sender, DragEventArgs e)
        {
            if (this.adorner != null)
			this.adorner.Remove();
			e.Handled = true;
        }

As shown in the example you have to revert the effects for the background color or the changes in the drop area after the drag and drop operation is finished. You also have to take care of it.

Conclusion

DragDropBehaviour is the base class of DragDropsBehaviors. It provides a high-level API to handle the operation of drag and drops functionality. You can drag and drop elements within and across different structures in WPF and can build a flexible WPF drag and drop application using the MVVM pattern.

Drag and Drop in WPF using Behavior

WPF-using-Behavior

Drag and drop software improves productivity and user experiences, but some of the application hadoffered drag and drop functionality because they believe it’s really hard. In this blog, we will discuss drag and drop functionality.

DragDropBehaviour is the base class of DragDropsBehaviors. It provides a high-level API to handle the operation of drag and drops functionality. When we control drag and drop functionality it will call automatically.

Table of Content

DragDropBehaviour class is inherited from the other class. So, it can connect with the other classes. You can be drag CandidateViewModel hence it implements an idraggable interface.

The CandidateViewModel can be dropped so it implements an idroppable interface.The ViewModel can be drag and drop so it implements both idragable and idropable.

Behavior Section

Framework behavior starts the drag process. It records the queries for the dragged Data type.When framework behavior is dropped on the framework at the time operation start. It is a subclass of system.window.UIElement class. That we normally see on WPF.

When ListboxBehaviour is dropped on List box at that time operation will perform.

View

Treeview: In Treeview, every element is also a framework element. So in the XAML file in declaration framework behavior and framework element drop behavior are used.

CandidateView: The candidate is candidate framework element, using them we can do drag. The candidate is draping Listbox so for that it uses listboxDropBehaviour class.

The main purpose of dragging is to select the data which transfers it along with defining the data which passed by dragging and it decides the area when the mouse hovers around the screen the informs the system.

iDragabble interface the following:





interface IDragable
    {
        /// Type of the data item
        Type DataType{get;}
        /// Remove the object collection
                void Remove (object i);
    }

Remove method can be used to remove the source data which is a copy operation. Do not simply it. You can add it to your application according to your requirement and improve its performance.

Creating an attached behaviourusing WPF

Basic step to create attached behaviour

  1. Use a public static class.
  2. Add a static dependency property and associated PropertyChangedCallback method.
  3. Add a static method that is static setter and getter.
  4. Add any static method.
  5. Add needed code.


Handling Drag and Drop in WPF

You will need a particular static object if you are handling drag and drop in WPF. This will help you to handle drag and drop.

Predefine data will be in the DataFormat class which will the data which is being dragged and drop. This is used to identify the data. If you are not familiar with the DataObject or iDataObject then you should first understand those concepts by which you can easily call the methods.

If you want to perform drag and drop then you should know which data you have to handle while you are performing drag and drop. You should have information that if selected data is being handled properly or not and what is the type of the selected data. You have an option to handle the behavior of the data behind the code. You can use the PreciewDrop event.

Writing a drop behaviour

  1. Create new class name is DropBehavior.
  2. The class both are public and static.
  3. Add DependencyProperty called PreviewDropCommand Property.
  4. Write the setter and getter method.
  5. Write the Propertycallback method.
DropBehavior.cs
using System.Windows.Input;
using System.Windows;

namespace MVVM
{
    

Using the behavior int the Xaml

Now you can add the data in the grid or the UI Element but cannot perform the drag and drop. If you try to drag and drop in the textbox then it will not work. The event will not be fired.

Example:

Add Dropbehavior to a user control and you can add the DropBehavior to a grid.
 


<usercontrolx: allowdrop="True" class="DropBehaviorExample.ExampleView" d:designheight="300" d:designwidth="400" mc:ignorable="d" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mvvm="clr-namespace:MVVM" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<grid mvvm:dropbehavior.previewdropcommand="{Binding PreviewDropCommand}">
</grid>

</usercontrolx:>

Implementing the ICommand in the ViewModel:

You will need the following code in the ViewModel

public ICommandPreviewDropCommand
{
    get { return _PreviewDropCommand ?? (_PreviewDropCommand = new RelayCommand(HandlePreviewDrop)); }
    set
    {
        _PreviewDropCommand = value;
		NotifyPropertyChanged("PreviewDropCommand");
    }
} 
	private ICommand _PreviewDropCommand;

	The method encapsulated in the relay command
	private void HandlePreviewDrop(object in object)
	{
		IDataObjectido = inObject as IDataObject;
		if (null == ido) return;

		// Get all the possible format
		string [] formats = ido.GetFormats();
 }

Wants to Talk with Our Highly Skilled WPF Developer ?

Your Search ends here.


The goal of the drag and drop operation

  1. It gives you the information that the dragged item can be placed in that particular place or not.
  2. Transfer data to the destination.
  3. Remove data from a source.

Below is iDraggable interface:

interface IDropable
    {
       
 /// Type of the data item ///  Type DataType{ get; } ///  /// Drop data into the collection. ///  ///The data to be dropped ///optional: The index location to insert the data void Drop(object data,double index = -1); }
 

Data type property will define the type of data which helps to put the data in the right place.

You have to do this operation in the view model because it makes it easier to just do drag and drop and you can also add more elements.

The data will be added to the dataset when using the Drop method. As we have seen earlier that data is being added to the Listbox.

You can create a drop method and later you can bound to any mouse event or mouse action. For example, giving background color effects when hovering over the mouse pointer shows a good impression of a programmer. Also changing the thickness of the border of the box by extending or shrinking it or to change the style of the border and by doing many other effects you can show the user that you are dropping your data here(at this place).

As it is shown in the below example.

private void SetDragDropEffects(DragEventArgs e)
        {
			e.Effects = DragDropEffects.None;  //default to None

            if (e.Data.GetDataPresent(dataType))
            {
				e.Effects = DragDropEffects.Move;
            }
        }

And when the data is dropped then also it is necessary to remove the effect which you provided while accepting the data. For this purpose we have developed a program which is as follows :

void AssociatedObject_DragLeave(object sender, DragEventArgs e)
        {
            if (this.adorner != null)
			this.adorner.Remove();
			e.Handled = true;
        }

As shown in the example you have to revert the effects for the background color or the changes in the drop area after the drag and drop operation is finished. You also have to take care of it.

Conclusion

DragDropBehaviour is the base class of DragDropsBehaviors. It provides a high-level API to handle the operation of drag and drops functionality. You can drag and drop elements within and across different structures in WPF and can build a flexible WPF drag and drop application using the MVVM pattern.