...

Что за программа drag and drop

Drag and drop

Drag and drop is an intuitive way to transfer data within an application or between applications on the Windows desktop. Drag and drop lets the user transfer data between applications or within an application using a standard gesture (press-hold-and-pan with the finger or press-and-pan with a mouse or a stylus).

The drag source, which is the application or area where the drag gesture is triggered, provides the data to be transferred by filling a data package object that can contain standard data formats, including text, RTF, HTML, bitmaps, storage items or custom data formats. The source also indicates the kind of operations it supports: copy, move or link. When the pointer is released, drop occurs. The drop target, which is the application or area underneath the pointer, processes the data package and returns the type of operation it performed.

During drag and drop, the drag UI provides a visual indication of the type of drag-and-drop operation that’s taking place. This visual feedback is initially provided by the source but can be changed by the targets as the pointer moves over them.

Modern drag and drop is available on all devices that support UWP. It allows data transfer between or within any kind of application, including Classic Windows apps, although this article focuses on the XAML API for modern drag and drop. Once implemented, drag and drop works seamlessly in all directions, including app-to-app, app-to-desktop, and desktop-to app.

Here’s an overview of what you need to do to enable drag and drop in your app:

  1. Enable dragging on an element by setting its CanDrag property to true.
  2. Build the data package. The system handles images and text automatically, but for other content, you’ll need to handle the DragStarting and DropCompleted events and use them to construct your own data package.
  3. Enable dropping by setting the AllowDrop property to true on all the elements that can receive dropped content.
  4. Handle the DragOver event to let the system know what type of drag operations the element can receive.
  5. Process the Drop event to receive the dropped content.

Enable dragging

To enable dragging on an element, set its CanDrag property to true. This make the element—and the elements it contains, in the case of collections like ListView—draggable.

Be specific about what’s draggable. Users won’t want to drag everything in your app, only certain items, such as images or text.

You don’t need to do any other work to allow dragging, unless you want to customize the UI (which is covered later in this article). Dropping requires a few more steps.

Construct a data package

In most cases, the system will construct a data package for you. The system automatically handles:

For other content, you’ll need to handle the DragStarting and DropCompleted events and use them to construct your own DataPackage.

Enable dropping

The following markup shows how to set a specific area of the app as valid for dropping by using the AllowDrop in XAML. If a user tries to drop somewhere else, the system won’t let them. If you want users to be able to drop items anywhere on your app, set the entire background as a drop target.

 Drop anywhere in the blue area  

Handle the DragOver event

The DragOver event fires when a user has dragged an item over your app, but not yet dropped it. In this handler, you need to specify what kind of operations your app supports by using the AcceptedOperation property. Copy is the most common.

private void Grid_DragOver(object sender, DragEventArgs e)

Process the Drop event

The Drop event occurs when the user releases items in a valid drop area. Process them by using the DataView property.

For simplicity in the example below, we’ll assume the user dropped a single photo and access it directly. In reality, users can drop multiple items of varying formats simultaneously. Your app should handle this possibility by checking what types of files were dropped and how many there are, and process each accordingly. You should also consider notifying the user if they’re trying to do something your app doesn’t support.

private async void Grid_Drop(object sender, DragEventArgs e) < if (e.DataView.Contains(StandardDataFormats.StorageItems)) < var items = await e.DataView.GetStorageItemsAsync(); if (items.Count >0) < var storageFile = items[0] as StorageFile; var bitmapImage = new BitmapImage(); bitmapImage.SetSource(await storageFile.OpenAsync(FileAccessMode.Read)); // Set the image on the main page to the dropped image Image.Source = bitmapImage; >> > 

Customize the UI

The system provides a default UI for dragging and dropping. However, you can also choose to customize various parts of the UI by setting custom captions and glyphs, or by opting not to show a UI at all. To customize the UI, use the DragEventArgs.DragUIOverride property.

private void Grid_DragOverCustomized(object sender, DragEventArgs e) < e.AcceptedOperation = DataPackageOperation.Copy; e.DragUIOverride.Caption = "Custom text here"; // Sets custom UI text // Sets a custom glyph e.DragUIOverride.SetContentFromBitmapImage( new BitmapImage( new Uri("ms-appx:///Assets/CustomImage.png", UriKind.RelativeOrAbsolute))); e.DragUIOverride.IsCaptionVisible = true; // Sets if the caption is visible e.DragUIOverride.IsContentVisible = true; // Sets if the dragged content is visible e.DragUIOverride.IsGlyphVisible = true; // Sets if the glyph is visibile >

Open a context menu on an item you can drag with touch

When using touch, dragging a UIElement and opening its context menu share similar touch gestures; each begins with a press and hold. Here’s how the system disambiguates between the two actions for elements in your app that support both:

  • If a user presses and holds an item and begins dragging it within 500 milliseconds, the item is dragged and the context menu is not shown.
  • If the user presses and holds but does not drag within 500 milliseconds, the context menu is opened.
  • After the context menu is open, if the user tries to drag the item (without lifting their finger), the context menu is dismissed and the drag will start.

Designate an item in a ListView or GridView as a folder

You can specify a ListViewItem or GridViewItem as a folder. This is particularly useful for TreeView and File Explorer scenarios. To do so, explicitly set the AllowDrop property to True on that item.

The system will automatically show the appropriate animations for dropping into a folder versus a non-folder item. Your app code must continue to handle the Drop event on the folder item (as well as on the non-folder item) in order to update the data source and add the dropped item to the target folder.

Enable drag and drop reordering within ListViews

ListViews support drag-based reordering out of the box, using an API very similar to the CanDrop API described in this article. At minimum, you add the AllowDrop and CanReorderItems properties.

Implementing custom drag and drop

The UIElement class does most of the work of implementing drag-and-drop for you. But if you want, you can implement your own version by using the APIs in the Windows.ApplicationModel.DataTransfer.DragDrop.Core namespace.

Functionality WinRT API
Enable dragging CoreDragOperation
Create a data package DataPackage
Hand off drag to the shell CoreDragOperation.StartAsync
Receive drop from the shell CoreDragDropManager
ICoreDropOperationTarget

Drag and Drop

Drag and drop refers to data transfers in which a mouse or other pointing device is used to specify both the data source and its destination. In a typical drag and drop operation, a user selects the object to be transferred by moving the mouse pointer to it and holding down either the left button or some other button designated for this purpose. While continuing to hold down the button, the user initiates the transfer by dragging the object to its destination, which can be any OLE container. Drag and drop provides exactly the same functionality as the OLE clipboard copy and paste but adds visual feedback and eliminates the need for menus. In fact, if an application supports clipboard copy and paste, little extra is needed to support drag and drop.

During an OLE drag and drop operation, the following three separate pieces of code are used.

Drag-and-drop code source Implementation and use
IDropSource interface Implemented by the object containing the dragged data, referred to as the drag source.
IDropTarget interface Implemented by the object that is intended to accept the drop, referred to as the drop target.
DoDragDrop function Implemented by OLE and used to initiate a drag and drop operation. After the operation is in progress, it facilitates communication between the drag source and the drop target.

The IDropSource and IDropTarget interfaces can be implemented in either a container or in an object application. The role of drag source or drop target is not limited to any one type of OLE application.

The OLE function DoDragDrop implements a loop that tracks mouse and keyboard movement until such time as the drag is canceled or a drop occurs. DoDragDrop is the key function in the drag and drop process, facilitating communication between the drag source and drop target.

During a drag and drop operation, three types of feedback can be displayed to the user.

Type of feedback Description
Source feedback Provided by the drag source, the source feedback indicates the data is being dragged and does not change during the course of the drag. Typically, the data is highlighted to signal it has been selected.
Pointer feedback Provided by the drag source, the pointer feedback indicates what happens if the mouse is released at any given moment. Pointer feedback changes continually as the user moves the mouse and/or presses a modifier key. For example, if the pointer is moved into a window that cannot accept a drop, the pointer changes to the “not allowed” symbol.
Target feedback Provided by the drop target, target feedback indicates where the drop is to occur.

Метод создания DRAG and DROP эффекта

Придя впервые к технологии DRAG and DROP столкнулся с очень тяжелым её описанием (Это мое субъективное мнение. Прошу с ним не соглашаться, а перечитать все что только можно и посмотреть на этот вопрос с многих сторон). И решил написать пару статей, нацеленных на начинающих разработчиков, кто хочет познать дзен.

Статья будет состоять из двух частей:

  • Метод создания DRAG and DROP эффектов.
  • Практическое применение полученных знаний для создание сортировки при помощи DRAG and DROP

Параграф №1 Метод создания DRAG and DROP эффекта

Перед началом глубокого разбора, посмотрим поверхностно. Представьте себя в роли грузчика, вам необходимо перемесить коробку с одного места на другое. Для грузчика это «Ну взял, ну перенес. Готово!», а для программиста “Подошел к коробке, наклонился, взял коробку, поднял коробку, прошел N шагов, наклонился, отпустил коробку.”. Я это к тому, что перед началом работы проиграйте все в голове, по шагам и вы станете гораздо ближе к истине.

Я хочу оговориться, что методов создания данного эффекта несколько и обязательно прочтите о всех. Я воспользуюсь тем, который на данный момент считаю самым удобным.

При создании DRAG and DROP первым шагом необходимо объекту, который мы будем перемещать, присвоить значение draggable=’true’.

   .ddd 
Pervii 1

,
На первом этапе я хочу показать сам процесс, а после мы его распространим на все объекты. Мы сейчас работаем в JS и как вам известно, в браузере существуют различные события, к которым мы можем привязать свои последовательности действий. Давайте разберем необходимые события для создания DRAG and DROP:

dragstart — происходит, когда пользователь начинает перетаскивать элемент.
drag — происходит, когда элемент перетаскивается.
dragend — происходит, когда пользователь закончил перетаскивание элемента.
dragenter — происходит, когда перетаскиваемый элемент попадает в целевой объект.
dragleave — происходит, когда перетаскиваемый элемент покидает целевой объект.
dragover — происходит, когда перетаскиваемый элемент находится над целью.
drop — происходит, когда перетаскиваемый элемент падает на целевой объект.

Теперь очень важная информация! События делятся на две группы. Для перемещаемого элемента (тот кого мы перетаскиваем): dragstart, Drag, Dragend. Для принимающего элемента (куда перетаскиваем): Dragenter, Dragleave, Dragover, Drop. И эти события не могут работать наоборот, но они могут работать друг без друга.

К примеру: Необходимо переместить объект и оставить его там, где мы отпустили кнопку мыши. Эта задача не требует принимающей части.

   .ddd 
Pervii 1
Vtoroy 2
Tretii 3
Chetverty 4
Pyatii 5

Бесспорно, пример сделан на коленке, но он замечательно иллюстрирует не обязательность принимающего объекта.

Параграф №2. Не работает DROP в DRAG and DROP

Когда вы попробуете все события, вы обнаружите что drop не работает. Это разработчики данного метода делают атата тем, кто решил «И это всё… Хух, ерунда».

Ну тут все просто, перед событием drop необходимо на этот же элемент повесить событие

d2.addEventListener('dragover',function() < event.preventDefault(); >); 

При подготовке материала использовались источники:
https://learn.microsoft.com/en-us/windows/apps/design/input/drag-and-drop
https://learn.microsoft.com/en-us/windows/win32/com/drag-and-drop
https://habr.com/ru/articles/463463/

Добавить комментарий