Убраны синхронные методы
This commit is contained in:
49
Lattice.UI.DragDrop.WinUI/Behaviors/DragSource.cs
Normal file
49
Lattice.UI.DragDrop.WinUI/Behaviors/DragSource.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using Microsoft.UI.Xaml;
|
||||
|
||||
namespace Lattice.UI.DragDrop.WinUI.Behaviors;
|
||||
|
||||
/// <summary>
|
||||
/// Attached properties для DragSource.
|
||||
/// </summary>
|
||||
public static class DragSource
|
||||
{
|
||||
public static readonly DependencyProperty IsEnabledProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"IsEnabled",
|
||||
typeof(bool),
|
||||
typeof(DragSource),
|
||||
new PropertyMetadata(false, OnIsEnabledChanged));
|
||||
|
||||
public static readonly DependencyProperty DragDataProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DragData",
|
||||
typeof(object),
|
||||
typeof(DragSource),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
public static bool GetIsEnabled(UIElement element) =>
|
||||
(bool)element.GetValue(IsEnabledProperty);
|
||||
|
||||
public static void SetIsEnabled(UIElement element, bool value) =>
|
||||
element.SetValue(IsEnabledProperty, value);
|
||||
|
||||
public static object GetDragData(UIElement element) =>
|
||||
element.GetValue(DragDataProperty);
|
||||
|
||||
public static void SetDragData(UIElement element, object value) =>
|
||||
element.SetValue(DragDataProperty, value);
|
||||
|
||||
private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is not UIElement element) return;
|
||||
|
||||
// TODO: Здесь нужно создать экземпляр WinUIDragSourceBehavior
|
||||
// и прикрепить его к элементу через DI
|
||||
// Пока что устанавливаем данные в Tag
|
||||
if ((bool)e.NewValue)
|
||||
{
|
||||
var data = GetDragData(element);
|
||||
element.Tag = data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,58 +1,31 @@
|
||||
using Lattice.Core.Geometry;
|
||||
using Lattice.Core.DragDrop.Models;
|
||||
using Lattice.Core.Geometry;
|
||||
using Lattice.UI.DragDrop.Behaviors;
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Microsoft.UI.Xaml.Input;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Lattice.UI.DragDrop.WinUI.Behaviors;
|
||||
|
||||
/// <summary>
|
||||
/// Поведение источника перетаскивания для WinUI UIElement.
|
||||
/// Исправленная версия с правильной очисткой ресурсов.
|
||||
/// Поведение источника перетаскивания для WinUI FrameworkElement.
|
||||
/// </summary>
|
||||
public static class WinUIDragSourceBehavior
|
||||
public class WinUIDragSourceBehavior : DragSourceBehaviorBase<FrameworkElement>
|
||||
{
|
||||
#region Вложенные типы
|
||||
|
||||
private sealed class DragSourceContext : IDisposable
|
||||
{
|
||||
public Point DragStartPosition { get; set; }
|
||||
public bool IsDragging { get; set; }
|
||||
public UIElement? CurrentDragElement { get; set; }
|
||||
public object? DragData { get; set; }
|
||||
public Action<UIElement>? DragStartedHandler { get; set; }
|
||||
public Action<UIElement, Core.DragDrop.Enums.DragDropEffects>? DragCompletedHandler { get; set; }
|
||||
public Core.DragDrop.Enums.DragDropEffects AllowedEffects { get; set; }
|
||||
= Core.DragDrop.Enums.DragDropEffects.Copy | Core.DragDrop.Enums.DragDropEffects.Move;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
DragStartedHandler = null;
|
||||
DragCompletedHandler = null;
|
||||
DragData = null;
|
||||
CurrentDragElement = null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Прикрепленные свойства
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для привязки данных перетаскивания.
|
||||
/// Прикрепленное свойство для данных перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DragDataProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DragData",
|
||||
typeof(object),
|
||||
typeof(WinUIDragSourceBehavior),
|
||||
new PropertyMetadata(null, OnDragDataChanged));
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для включения перетаскивания.
|
||||
/// Прикрепленное свойство для включения перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty IsEnabledProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
@@ -62,368 +35,256 @@ public static class WinUIDragSourceBehavior
|
||||
new PropertyMetadata(false, OnIsEnabledChanged));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для разрешенных эффектов перетаскивания.
|
||||
/// Получает значение DragData.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty AllowedEffectsProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"AllowedEffects",
|
||||
typeof(Core.DragDrop.Enums.DragDropEffects),
|
||||
typeof(WinUIDragSourceBehavior),
|
||||
new PropertyMetadata(Core.DragDrop.Enums.DragDropEffects.Copy | Core.DragDrop.Enums.DragDropEffects.Move));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для обработчика начала перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DragStartedHandlerProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DragStartedHandler",
|
||||
typeof(Action<UIElement>),
|
||||
typeof(WinUIDragSourceBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для обработчика завершения перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DragCompletedHandlerProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DragCompletedHandler",
|
||||
typeof(Action<UIElement, Core.DragDrop.Enums.DragDropEffects>),
|
||||
typeof(WinUIDragSourceBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для обработчика создания данных перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DragDataFactoryProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DragDataFactory",
|
||||
typeof(Func<UIElement, Task<object>>),
|
||||
typeof(WinUIDragSourceBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
#endregion
|
||||
|
||||
#region Статические поля
|
||||
|
||||
private static readonly ConditionalWeakTable<UIElement, DragSourceContext> _contexts = new();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Методы доступа к свойствам
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства DragData для указанного элемента.
|
||||
/// </summary>
|
||||
public static object GetDragData(UIElement element) =>
|
||||
element.GetValue(DragDataProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства DragData для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetDragData(UIElement element, object value) =>
|
||||
element.SetValue(DragDataProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства IsEnabled для указанного элемента.
|
||||
/// </summary>
|
||||
public static bool GetIsEnabled(UIElement element) =>
|
||||
(bool)element.GetValue(IsEnabledProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства IsEnabled для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetIsEnabled(UIElement element, bool value) =>
|
||||
element.SetValue(IsEnabledProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства AllowedEffects для указанного элемента.
|
||||
/// </summary>
|
||||
public static Core.DragDrop.Enums.DragDropEffects GetAllowedEffects(UIElement element) =>
|
||||
(Core.DragDrop.Enums.DragDropEffects)element.GetValue(AllowedEffectsProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства AllowedEffects для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetAllowedEffects(UIElement element, Core.DragDrop.Enums.DragDropEffects value) =>
|
||||
element.SetValue(AllowedEffectsProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает обработчик начала перетаскивания.
|
||||
/// </summary>
|
||||
public static Action<UIElement> GetDragStartedHandler(UIElement element) =>
|
||||
(Action<UIElement>)element.GetValue(DragStartedHandlerProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает обработчик начала перетаскивания.
|
||||
/// </summary>
|
||||
public static void SetDragStartedHandler(UIElement element, Action<UIElement> value) =>
|
||||
element.SetValue(DragStartedHandlerProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает обработчик завершения перетаскивания.
|
||||
/// </summary>
|
||||
public static Action<UIElement, Core.DragDrop.Enums.DragDropEffects> GetDragCompletedHandler(UIElement element) =>
|
||||
(Action<UIElement, Core.DragDrop.Enums.DragDropEffects>)element.GetValue(DragCompletedHandlerProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает обработчик завершения перетаскивания.
|
||||
/// </summary>
|
||||
public static void SetDragCompletedHandler(UIElement element, Action<UIElement, Core.DragDrop.Enums.DragDropEffects> value) =>
|
||||
element.SetValue(DragCompletedHandlerProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает фабрику данных перетаскивания.
|
||||
/// </summary>
|
||||
public static Func<UIElement, Task<object>> GetDragDataFactory(UIElement element) =>
|
||||
(Func<UIElement, Task<object>>)element.GetValue(DragDataFactoryProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает фабрику данных перетаскивания.
|
||||
/// </summary>
|
||||
public static void SetDragDataFactory(UIElement element, Func<UIElement, Task<object>> value) =>
|
||||
element.SetValue(DragDataFactoryProperty, value);
|
||||
|
||||
#endregion
|
||||
|
||||
#region Обработчики изменений свойств
|
||||
|
||||
private static void OnDragDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
public static object GetDragData(FrameworkElement element)
|
||||
{
|
||||
if (d is UIElement element)
|
||||
{
|
||||
if (_contexts.TryGetValue(element, out var context))
|
||||
{
|
||||
context.DragData = e.NewValue;
|
||||
}
|
||||
}
|
||||
return element.GetValue(DragDataProperty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение DragData.
|
||||
/// </summary>
|
||||
public static void SetDragData(FrameworkElement element, object value)
|
||||
{
|
||||
element.SetValue(DragDataProperty, value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение IsEnabled.
|
||||
/// </summary>
|
||||
public static bool GetIsEnabled(FrameworkElement element)
|
||||
{
|
||||
return (bool)element.GetValue(IsEnabledProperty);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение IsEnabled.
|
||||
/// </summary>
|
||||
public static void SetIsEnabled(FrameworkElement element, bool value)
|
||||
{
|
||||
element.SetValue(IsEnabledProperty, value);
|
||||
}
|
||||
|
||||
private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
{
|
||||
if (d is UIElement element)
|
||||
if (d is FrameworkElement element)
|
||||
{
|
||||
// Получаем или создаем экземпляр поведения через Attached Property
|
||||
var behavior = GetBehavior(element);
|
||||
|
||||
if ((bool)e.NewValue)
|
||||
{
|
||||
EnableDrag(element);
|
||||
if (behavior == null)
|
||||
{
|
||||
behavior = new WinUIDragSourceBehavior();
|
||||
SetBehavior(element, behavior);
|
||||
}
|
||||
|
||||
behavior.AssociatedElement = element;
|
||||
}
|
||||
else
|
||||
{
|
||||
DisableDrag(element);
|
||||
if (behavior != null)
|
||||
{
|
||||
behavior.Detach();
|
||||
SetBehavior(element, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Включение/выключение перетаскивания
|
||||
|
||||
private static void EnableDrag(UIElement element)
|
||||
public WinUIDragSourceBehavior()
|
||||
: base(ServiceProviderHelper.GetServiceProvider())
|
||||
{
|
||||
if (_contexts.TryGetValue(element, out _))
|
||||
return;
|
||||
|
||||
var context = new DragSourceContext
|
||||
{
|
||||
DragData = GetDragData(element),
|
||||
DragStartedHandler = GetDragStartedHandler(element),
|
||||
DragCompletedHandler = GetDragCompletedHandler(element),
|
||||
AllowedEffects = GetAllowedEffects(element)
|
||||
};
|
||||
|
||||
_contexts.Add(element, context);
|
||||
}
|
||||
|
||||
protected override void SubscribeToEvents(FrameworkElement element)
|
||||
{
|
||||
element.PointerPressed += OnPointerPressed;
|
||||
element.PointerMoved += OnPointerMoved;
|
||||
element.PointerReleased += OnPointerReleased;
|
||||
element.PointerCanceled += OnPointerCanceled;
|
||||
element.PointerCaptureLost += OnPointerCaptureLost;
|
||||
element.Unloaded += OnElementUnloaded;
|
||||
element.LostFocus += OnLostFocus;
|
||||
}
|
||||
|
||||
private static void DisableDrag(UIElement element)
|
||||
protected override void UnsubscribeFromEvents(FrameworkElement element)
|
||||
{
|
||||
element.PointerPressed -= OnPointerPressed;
|
||||
element.PointerMoved -= OnPointerMoved;
|
||||
element.PointerReleased -= OnPointerReleased;
|
||||
element.PointerCanceled -= OnPointerCanceled;
|
||||
element.PointerCaptureLost -= OnPointerCaptureLost;
|
||||
element.Unloaded -= OnElementUnloaded;
|
||||
element.LostFocus -= OnLostFocus;
|
||||
}
|
||||
|
||||
if (_contexts.TryGetValue(element, out var context))
|
||||
private void OnPointerPressed(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
if (AssociatedElement == null) return;
|
||||
|
||||
var point = e.GetCurrentPoint(AssociatedElement);
|
||||
OnInteractionStarted(new Point(point.Position.X, point.Position.Y));
|
||||
}
|
||||
|
||||
private void OnPointerMoved(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
if (AssociatedElement == null) return;
|
||||
|
||||
var point = e.GetCurrentPoint(AssociatedElement);
|
||||
OnInteractionMoved(new Point(point.Position.X, point.Position.Y));
|
||||
}
|
||||
|
||||
private void OnPointerReleased(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
OnInteractionEnded();
|
||||
}
|
||||
|
||||
private void OnPointerCanceled(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
OnInteractionCancelled();
|
||||
}
|
||||
|
||||
private void OnPointerCaptureLost(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
OnInteractionCancelled();
|
||||
}
|
||||
|
||||
private void OnLostFocus(object sender, RoutedEventArgs e)
|
||||
{
|
||||
OnInteractionCancelled();
|
||||
}
|
||||
|
||||
protected override Point ConvertToScreenCoordinates(Point point)
|
||||
{
|
||||
if (AssociatedElement == null)
|
||||
return point;
|
||||
|
||||
var transform = AssociatedElement.TransformToVisual(null);
|
||||
var screenPoint = transform.TransformPoint(new Windows.Foundation.Point(point.X, point.Y));
|
||||
return new Point(screenPoint.X, screenPoint.Y);
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public override async Task<(bool CanStart, DragInfo? DragInfo)> CanStartDragAsync()
|
||||
{
|
||||
if (AssociatedElement == null)
|
||||
{
|
||||
context.Dispose();
|
||||
_contexts.Remove(element);
|
||||
return (false, null);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Обработчики событий
|
||||
|
||||
private static void OnPointerPressed(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
if (sender is UIElement element && _contexts.TryGetValue(element, out var context))
|
||||
var data = GetDragData(AssociatedElement);
|
||||
if (data == null)
|
||||
{
|
||||
var point = e.GetCurrentPoint(element);
|
||||
context.DragStartPosition = new Point(point.Position.X, point.Position.Y);
|
||||
context.CurrentDragElement = element;
|
||||
element.CapturePointer(e.Pointer);
|
||||
// Пробуем получить данные из Tag или других источников
|
||||
data = AssociatedElement.Tag ?? AssociatedElement.DataContext;
|
||||
}
|
||||
}
|
||||
|
||||
private static async void OnPointerMoved(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
if (sender is UIElement element && _contexts.TryGetValue(element, out var context))
|
||||
if (data == null)
|
||||
{
|
||||
if (context.IsDragging || context.CurrentDragElement == null)
|
||||
return;
|
||||
|
||||
var currentPoint = e.GetCurrentPoint(context.CurrentDragElement);
|
||||
var currentPosition = new Point(currentPoint.Position.X, currentPoint.Position.Y);
|
||||
|
||||
var distance = CalculateDistance(context.DragStartPosition, currentPosition);
|
||||
if (distance > 3.0) // Порог перетаскивания
|
||||
{
|
||||
context.IsDragging = true;
|
||||
await StartDragAsync(context.CurrentDragElement, currentPosition, context);
|
||||
}
|
||||
return (false, null);
|
||||
}
|
||||
|
||||
// Получаем начальную позицию в экранных координатах
|
||||
var startPosition = ConvertToScreenCoordinates(_dragStartPosition);
|
||||
|
||||
// Создаем DragInfo с учетом вашего конструктора
|
||||
var dragInfo = new DragInfo(
|
||||
data: data,
|
||||
allowedEffects: Core.DragDrop.Enums.DragDropEffects.Move |
|
||||
Core.DragDrop.Enums.DragDropEffects.Copy,
|
||||
startPosition: startPosition,
|
||||
source: this
|
||||
);
|
||||
|
||||
return (true, dragInfo);
|
||||
}
|
||||
|
||||
private static async Task StartDragAsync(UIElement element, Point currentPosition, DragSourceContext context)
|
||||
protected override void OnDragCompleted(DragInfo dragInfo, Core.DragDrop.Enums.DragDropEffects effects)
|
||||
{
|
||||
try
|
||||
{
|
||||
object? data = context.DragData;
|
||||
base.OnDragCompleted(dragInfo, effects);
|
||||
|
||||
// Если есть фабрика данных, используем ее
|
||||
var factory = GetDragDataFactory(element);
|
||||
if (factory != null)
|
||||
{
|
||||
data = await factory(element);
|
||||
}
|
||||
|
||||
if (data != null)
|
||||
{
|
||||
context.DragData = data;
|
||||
|
||||
// Вызываем обработчик начала перетаскивания
|
||||
context.DragStartedHandler?.Invoke(element);
|
||||
|
||||
// Устанавливаем визуальный эффект
|
||||
SetDragVisualState(element, true);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
System.Diagnostics.Debug.WriteLine($"Error starting drag: {ex.Message}");
|
||||
context.IsDragging = false;
|
||||
}
|
||||
// Визуальная обратная связь при завершении
|
||||
SetVisualState(AssociatedElement, "Normal");
|
||||
}
|
||||
|
||||
private static void OnPointerReleased(object sender, PointerRoutedEventArgs e)
|
||||
protected override void OnDragCancelled(DragInfo dragInfo)
|
||||
{
|
||||
CompleteDrag(sender as UIElement, Core.DragDrop.Enums.DragDropEffects.Copy);
|
||||
base.OnDragCancelled(dragInfo);
|
||||
|
||||
// Визуальная обратная связь при отмене
|
||||
SetVisualState(AssociatedElement, "Normal");
|
||||
}
|
||||
|
||||
private static void OnPointerCanceled(object sender, PointerRoutedEventArgs e)
|
||||
private void SetVisualState(FrameworkElement? element, string stateName)
|
||||
{
|
||||
CompleteDrag(sender as UIElement, Core.DragDrop.Enums.DragDropEffects.None);
|
||||
}
|
||||
|
||||
private static void OnPointerCaptureLost(object sender, PointerRoutedEventArgs e)
|
||||
{
|
||||
CompleteDrag(sender as UIElement, Core.DragDrop.Enums.DragDropEffects.None);
|
||||
}
|
||||
|
||||
private static void OnElementUnloaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is UIElement element)
|
||||
{
|
||||
DisableDrag(element);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Вспомогательные методы
|
||||
|
||||
private static void CompleteDrag(UIElement? element, Core.DragDrop.Enums.DragDropEffects effects)
|
||||
{
|
||||
if (element != null && _contexts.TryGetValue(element, out var context))
|
||||
{
|
||||
// Вызываем обработчик завершения перетаскивания
|
||||
context.DragCompletedHandler?.Invoke(element, effects);
|
||||
|
||||
// Сбрасываем визуальный эффект
|
||||
SetDragVisualState(element, false);
|
||||
|
||||
element.ReleasePointerCaptures();
|
||||
|
||||
ResetDragState(context);
|
||||
}
|
||||
}
|
||||
|
||||
private static void SetDragVisualState(UIElement element, bool isDragging)
|
||||
{
|
||||
// Для элементов, которые являются Control, используем VisualStateManager
|
||||
if (element is Control control)
|
||||
{
|
||||
// Пытаемся перейти к состоянию "Dragging" или "Normal"
|
||||
try
|
||||
{
|
||||
VisualStateManager.GoToState(control, isDragging ? "Dragging" : "Normal", true);
|
||||
VisualStateManager.GoToState(control, stateName, true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Если состояния не определены, меняем свойства напрямую
|
||||
control.Opacity = isDragging ? 0.7 : 1.0;
|
||||
// Fallback
|
||||
control.Opacity = 1.0;
|
||||
}
|
||||
}
|
||||
else
|
||||
else if (element != null)
|
||||
{
|
||||
// Для обычных UIElement меняем свойства напрямую
|
||||
element.Opacity = isDragging ? 0.7 : 1.0;
|
||||
// Альтернативная визуальная обратная связь для не-Control элементов
|
||||
element.Opacity = 1.0;
|
||||
}
|
||||
}
|
||||
|
||||
private static double CalculateDistance(Point p1, Point p2)
|
||||
// Attached property для хранения экземпляра поведения
|
||||
private static readonly DependencyProperty BehaviorProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"Behavior",
|
||||
typeof(WinUIDragSourceBehavior),
|
||||
typeof(WinUIDragSourceBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
private static WinUIDragSourceBehavior GetBehavior(FrameworkElement element)
|
||||
{
|
||||
var dx = p2.X - p1.X;
|
||||
var dy = p2.Y - p1.Y;
|
||||
return Math.Sqrt(dx * dx + dy * dy);
|
||||
return (WinUIDragSourceBehavior)element.GetValue(BehaviorProperty);
|
||||
}
|
||||
|
||||
private static void ResetDragState(DragSourceContext context)
|
||||
private static void SetBehavior(FrameworkElement element, WinUIDragSourceBehavior? value)
|
||||
{
|
||||
context.IsDragging = false;
|
||||
context.CurrentDragElement = null;
|
||||
context.DragStartPosition = default;
|
||||
element.SetValue(BehaviorProperty, value);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
/// <summary>
|
||||
/// Вспомогательный класс для получения IServiceProvider.
|
||||
/// </summary>
|
||||
internal static class ServiceProviderHelper
|
||||
{
|
||||
private static IServiceProvider? _serviceProvider;
|
||||
|
||||
#region Методы очистки
|
||||
|
||||
/// <summary>
|
||||
/// Очищает все ресурсы, связанные с поведением перетаскивания.
|
||||
/// </summary>
|
||||
public static void Cleanup()
|
||||
public static IServiceProvider GetServiceProvider()
|
||||
{
|
||||
var elements = new List<UIElement>();
|
||||
|
||||
foreach (var kvp in _contexts)
|
||||
if (_serviceProvider == null)
|
||||
{
|
||||
elements.Add(kvp.Key);
|
||||
// Ищем IServiceProvider в Application.Current.Resources
|
||||
if (Application.Current.Resources.TryGetValue("ServiceProvider", out var provider) &&
|
||||
provider is IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
"IServiceProvider не найден. Убедитесь, что ServiceProvider зарегистрирован в ресурсах приложения.");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var element in elements)
|
||||
{
|
||||
DisableDrag(element);
|
||||
}
|
||||
|
||||
_contexts.Clear();
|
||||
return _serviceProvider;
|
||||
}
|
||||
|
||||
#endregion
|
||||
public static void SetServiceProvider(IServiceProvider serviceProvider)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
}
|
||||
@@ -1,402 +1,345 @@
|
||||
using Microsoft.UI.Xaml;
|
||||
using Microsoft.UI.Xaml.Controls;
|
||||
using Lattice.Core.DragDrop.Models;
|
||||
using Lattice.Core.Geometry;
|
||||
using Lattice.UI.DragDrop.Behaviors;
|
||||
using Microsoft.UI.Xaml;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Lattice.UI.DragDrop.WinUI.Behaviors;
|
||||
|
||||
/// <summary>
|
||||
/// Поведение цели сброса для WinUI UIElement.
|
||||
/// </summary>
|
||||
public static class WinUIDropTargetBehavior
|
||||
namespace Lattice.UI.DragDrop.WinUI.Behaviors
|
||||
{
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для включения цели сброса.
|
||||
/// Поведение цели сброса для элементов WinUI.
|
||||
/// Позволяет элементам принимать данные при операции перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty IsEnabledProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"IsEnabled",
|
||||
typeof(bool),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(false, OnIsEnabledChanged));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для фильтрации принимаемых данных.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty AcceptsDataTypesProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"AcceptsDataTypes",
|
||||
typeof(Type[]),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для обработчика сброса.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DropHandlerProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DropHandler",
|
||||
typeof(Core.DragDrop.Abstractions.IDropTarget),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для отображения визуальной обратной связи.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty ShowVisualFeedbackProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"ShowVisualFeedback",
|
||||
typeof(bool),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(true));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для стиля визуальной обратной связи.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty FeedbackStyleProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"FeedbackStyle",
|
||||
typeof(Style),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для обработчика входа перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DragEnterHandlerProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DragEnterHandler",
|
||||
typeof(Action<UIElement>),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для обработчика выхода перетаскивания.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DragLeaveHandlerProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DragLeaveHandler",
|
||||
typeof(Action<UIElement>),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
/// <summary>
|
||||
/// Идентификатор свойства для обработчика сброса.
|
||||
/// </summary>
|
||||
public static readonly DependencyProperty DropHandlerActionProperty =
|
||||
DependencyProperty.RegisterAttached(
|
||||
"DropHandlerAction",
|
||||
typeof(Action<UIElement, object>),
|
||||
typeof(WinUIDropTargetBehavior),
|
||||
new PropertyMetadata(null));
|
||||
|
||||
// Словарь для отслеживания текущих перетаскиваемых элементов
|
||||
private static readonly Dictionary<UIElement, bool> _dragOverElements = new();
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства IsEnabled для указанного элемента.
|
||||
/// </summary>
|
||||
public static bool GetIsEnabled(UIElement element) =>
|
||||
(bool)element.GetValue(IsEnabledProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства IsEnabled для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetIsEnabled(UIElement element, bool value) =>
|
||||
element.SetValue(IsEnabledProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства AcceptsDataTypes для указанного элемента.
|
||||
/// </summary>
|
||||
public static Type[] GetAcceptsDataTypes(UIElement element) =>
|
||||
(Type[])element.GetValue(AcceptsDataTypesProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства AcceptsDataTypes для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetAcceptsDataTypes(UIElement element, Type[] value) =>
|
||||
element.SetValue(AcceptsDataTypesProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства DropHandler для указанного элемента.
|
||||
/// </summary>
|
||||
public static Core.DragDrop.Abstractions.IDropTarget GetDropHandler(UIElement element) =>
|
||||
(Core.DragDrop.Abstractions.IDropTarget)element.GetValue(DropHandlerProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства DropHandler для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetDropHandler(UIElement element, Core.DragDrop.Abstractions.IDropTarget value) =>
|
||||
element.SetValue(DropHandlerProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства ShowVisualFeedback для указанного элемента.
|
||||
/// </summary>
|
||||
public static bool GetShowVisualFeedback(UIElement element) =>
|
||||
(bool)element.GetValue(ShowVisualFeedbackProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства ShowVisualFeedback для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetShowVisualFeedback(UIElement element, bool value) =>
|
||||
element.SetValue(ShowVisualFeedbackProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает значение свойства FeedbackStyle для указанного элемента.
|
||||
/// </summary>
|
||||
public static Style GetFeedbackStyle(UIElement element) =>
|
||||
(Style)element.GetValue(FeedbackStyleProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает значение свойства FeedbackStyle для указанного элемента.
|
||||
/// </summary>
|
||||
public static void SetFeedbackStyle(UIElement element, Style value) =>
|
||||
element.SetValue(FeedbackStyleProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает обработчик входа перетаскивания.
|
||||
/// </summary>
|
||||
public static Action<UIElement> GetDragEnterHandler(UIElement element) =>
|
||||
(Action<UIElement>)element.GetValue(DragEnterHandlerProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает обработчик входа перетаскивания.
|
||||
/// </summary>
|
||||
public static void SetDragEnterHandler(UIElement element, Action<UIElement> value) =>
|
||||
element.SetValue(DragEnterHandlerProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает обработчик выхода перетаскивания.
|
||||
/// </summary>
|
||||
public static Action<UIElement> GetDragLeaveHandler(UIElement element) =>
|
||||
(Action<UIElement>)element.GetValue(DragLeaveHandlerProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает обработчик выхода перетаскивания.
|
||||
/// </summary>
|
||||
public static void SetDragLeaveHandler(UIElement element, Action<UIElement> value) =>
|
||||
element.SetValue(DragLeaveHandlerProperty, value);
|
||||
|
||||
/// <summary>
|
||||
/// Получает обработчик сброса.
|
||||
/// </summary>
|
||||
public static Action<UIElement, object> GetDropHandlerAction(UIElement element) =>
|
||||
(Action<UIElement, object>)element.GetValue(DropHandlerActionProperty);
|
||||
|
||||
/// <summary>
|
||||
/// Устанавливает обработчик сброса.
|
||||
/// </summary>
|
||||
public static void SetDropHandlerAction(UIElement element, Action<UIElement, object> value) =>
|
||||
element.SetValue(DropHandlerActionProperty, value);
|
||||
|
||||
private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Это поведение должно быть прикреплено к <see cref="FrameworkElement"/>, который должен выступать в качестве цели сброса.
|
||||
/// Поведение автоматически регистрирует элемент в системе перетаскивания и обрабатывает все аспекты операции сброса.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Для использования необходимо:
|
||||
/// 1. Создать экземпляр поведения с помощью <see cref="Attach"/> или через DI.
|
||||
/// 2. Переопределить методы <see cref="CanAcceptDrop"/> и <see cref="Drop"/> для реализации логики принятия данных.
|
||||
/// 3. При необходимости переопределить <see cref="DragOver"/> для настройки визуальной обратной связи.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public class WinUIDropTargetBehavior : DropTargetBehaviorBase<FrameworkElement>
|
||||
{
|
||||
if (d is UIElement element)
|
||||
private static readonly ConcurrentDictionary<FrameworkElement, WinUIDropTargetBehavior> _attachedBehaviors = new();
|
||||
private readonly WeakReference<FrameworkElement>? _weakElement;
|
||||
|
||||
/// <summary>
|
||||
/// Инициализирует новый экземпляр класса <see cref="WinUIDropTargetBehavior"/>.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">Провайдер сервисов.</param>
|
||||
/// <remarks>
|
||||
/// Конструктор создает экземпляр поведения, но не прикрепляет его к элементу.
|
||||
/// Для прикрепления используйте метод <see cref="Attach(FrameworkElement, IServiceProvider)"/>.
|
||||
/// </remarks>
|
||||
public WinUIDropTargetBehavior(IServiceProvider serviceProvider)
|
||||
: base(serviceProvider)
|
||||
{
|
||||
if ((bool)e.NewValue)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Инициализирует новый экземпляр класса <see cref="WinUIDropTargetBehavior"/>.
|
||||
/// </summary>
|
||||
/// <param name="serviceProvider">Провайдер сервисов.</param>
|
||||
/// <param name="element">Элемент, к которому прикрепляется поведение.</param>
|
||||
/// <remarks>
|
||||
/// Конструктор создает экземпляр поведения и сразу прикрепляет его к указанному элементу.
|
||||
/// </remarks>
|
||||
public WinUIDropTargetBehavior(IServiceProvider serviceProvider, FrameworkElement element)
|
||||
: base(serviceProvider)
|
||||
{
|
||||
AssociatedElement = element ?? throw new ArgumentNullException(nameof(element));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Прикрепляет поведение к указанному элементу.
|
||||
/// </summary>
|
||||
/// <param name="element">Элемент, к которому прикрепляется поведение.</param>
|
||||
/// <param name="serviceProvider">Провайдер сервисов.</param>
|
||||
/// <returns>
|
||||
/// Экземпляр поведения, прикрепленного к элементу. Если к элементу уже прикреплено поведение,
|
||||
/// возвращает существующий экземпляр.
|
||||
/// </returns>
|
||||
/// <exception cref="ArgumentNullException">
|
||||
/// Выбрасывается, когда <paramref name="element"/> или <paramref name="serviceProvider"/> равны null.
|
||||
/// </exception>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Этот метод обеспечивает, что к каждому элементу прикреплен только один экземпляр поведения.
|
||||
/// Если метод вызывается повторно для того же элемента, возвращается существующий экземпляр.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Прикрепленное поведение автоматически отслеживает изменения макета элемента и обновляет
|
||||
/// его границы в системе перетаскивания.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static WinUIDropTargetBehavior Attach(FrameworkElement element, IServiceProvider serviceProvider)
|
||||
{
|
||||
if (element == null) throw new ArgumentNullException(nameof(element));
|
||||
if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider));
|
||||
|
||||
return _attachedBehaviors.GetOrAdd(element, key =>
|
||||
{
|
||||
EnableDrop(element);
|
||||
var behavior = new WinUIDropTargetBehavior(serviceProvider, key);
|
||||
|
||||
// Подписка на события жизненного цикла элемента
|
||||
key.Unloaded += OnElementUnloaded;
|
||||
return behavior;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Открепляет поведение от указанного элемента.
|
||||
/// </summary>
|
||||
/// <param name="element">Элемент, от которого открепляется поведение.</param>
|
||||
/// <returns>
|
||||
/// true, если поведение было успешно откреплено; false, если поведение не было прикреплено к элементу.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// Этот метод освобождает все ресурсы, связанные с поведением, и отписывается от событий элемента.
|
||||
/// После вызова этого метода элемент перестает быть целью сброса.
|
||||
/// </remarks>
|
||||
public static bool Detach(FrameworkElement element)
|
||||
{
|
||||
if (element == null) return false;
|
||||
|
||||
if (_attachedBehaviors.TryRemove(element, out var behavior))
|
||||
{
|
||||
element.Unloaded -= OnElementUnloaded;
|
||||
behavior.Detach();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получает поведение, прикрепленное к указанному элементу.
|
||||
/// </summary>
|
||||
/// <param name="element">Элемент, для которого требуется получить поведение.</param>
|
||||
/// <returns>
|
||||
/// Экземпляр поведения, прикрепленного к элементу, или null, если поведение не прикреплено.
|
||||
/// </returns>
|
||||
public static WinUIDropTargetBehavior? GetAttachedBehavior(FrameworkElement element)
|
||||
{
|
||||
_attachedBehaviors.TryGetValue(element, out var behavior);
|
||||
return behavior;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Подписывается на события элемента.
|
||||
/// </summary>
|
||||
/// <param name="element">Элемент, к которому прикрепляется поведение.</param>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Этот метод подписывается на следующие события:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item><see cref="FrameworkElement.LayoutUpdated"/> - для отслеживания изменений макета</item>
|
||||
/// <item><see cref="FrameworkElement.SizeChanged"/> - для отслеживания изменений размера</item>
|
||||
/// <item><see cref="FrameworkElement.Loaded"/> - для инициализации при загрузке элемента</item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// Переопределите этот метод, чтобы добавить подписку на дополнительные события.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
protected override void SubscribeToEvents(FrameworkElement element)
|
||||
{
|
||||
if (element == null) return;
|
||||
|
||||
element.LayoutUpdated += OnLayoutUpdated;
|
||||
element.SizeChanged += OnSizeChanged;
|
||||
element.Loaded += OnLoaded;
|
||||
|
||||
// Если элемент уже загружен, сразу обновляем границы
|
||||
if (element.IsLoaded)
|
||||
{
|
||||
DisableDrop(element);
|
||||
UpdateBounds();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnableDrop(UIElement element)
|
||||
{
|
||||
element.AllowDrop = true;
|
||||
element.DragEnter += OnDragEnter;
|
||||
element.DragOver += OnDragOver;
|
||||
element.DragLeave += OnDragLeave;
|
||||
element.Drop += OnDrop;
|
||||
}
|
||||
|
||||
private static void DisableDrop(UIElement element)
|
||||
{
|
||||
element.AllowDrop = false;
|
||||
element.DragEnter -= OnDragEnter;
|
||||
element.DragOver -= OnDragOver;
|
||||
element.DragLeave -= OnDragLeave;
|
||||
element.Drop -= OnDrop;
|
||||
}
|
||||
|
||||
private static void OnDragEnter(object sender, DragEventArgs e)
|
||||
{
|
||||
var element = sender as UIElement;
|
||||
if (element == null) return;
|
||||
|
||||
// Проверяем, можно ли принять данные
|
||||
if (CanAcceptData(element, e.DataView))
|
||||
/// <summary>
|
||||
/// Отписывается от событий элемента.
|
||||
/// </summary>
|
||||
/// <param name="element">Элемент, от которого отписывается поведение.</param>
|
||||
/// <remarks>
|
||||
/// Этот метод отписывается от всех событий, на которые подписался <see cref="SubscribeToEvents"/>.
|
||||
/// </remarks>
|
||||
protected override void UnsubscribeFromEvents(FrameworkElement element)
|
||||
{
|
||||
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
|
||||
if (element == null) return;
|
||||
|
||||
// Визуальная обратная связь
|
||||
ShowVisualFeedback(element, true);
|
||||
|
||||
// Вызываем пользовательский обработчик
|
||||
GetDragEnterHandler(element)?.Invoke(element);
|
||||
|
||||
// Добавляем в словарь
|
||||
_dragOverElements[element] = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.None;
|
||||
element.LayoutUpdated -= OnLayoutUpdated;
|
||||
element.SizeChanged -= OnSizeChanged;
|
||||
element.Loaded -= OnLoaded;
|
||||
}
|
||||
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private static void OnDragOver(object sender, DragEventArgs e)
|
||||
{
|
||||
var element = sender as UIElement;
|
||||
if (element == null) return;
|
||||
|
||||
if (CanAcceptData(element, e.DataView))
|
||||
/// <summary>
|
||||
/// Получает границы элемента в экранных координатах.
|
||||
/// </summary>
|
||||
/// <param name="element">Элемент, границы которого нужно получить.</param>
|
||||
/// <returns>
|
||||
/// Прямоугольник, описывающий границы элемента в экранных координатах.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Метод использует преобразование координат через <see cref="UIElement.TransformToVisual"/>
|
||||
/// для получения глобальных координат элемента.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Если элемент не прикреплен к визуальному дереву или его границы не могут быть вычислены,
|
||||
/// возвращается пустой прямоугольник.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
protected override Rect GetScreenBounds(FrameworkElement element)
|
||||
{
|
||||
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
|
||||
if (element == null || !element.IsLoaded)
|
||||
return Rect.Empty;
|
||||
|
||||
// Обновляем визуальную обратную связь на основе позиции
|
||||
var position = e.GetPosition(element);
|
||||
UpdateVisualFeedback(element, position);
|
||||
}
|
||||
else
|
||||
{
|
||||
e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.None;
|
||||
}
|
||||
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private static void OnDragLeave(object sender, DragEventArgs e)
|
||||
{
|
||||
var element = sender as UIElement;
|
||||
if (element == null) return;
|
||||
|
||||
// Скрываем визуальную обратную связь
|
||||
ShowVisualFeedback(element, false);
|
||||
|
||||
// Вызываем пользовательский обработчик
|
||||
GetDragLeaveHandler(element)?.Invoke(element);
|
||||
|
||||
// Удаляем из словаря
|
||||
_dragOverElements.Remove(element);
|
||||
}
|
||||
|
||||
private static void OnDrop(object sender, DragEventArgs e)
|
||||
{
|
||||
var element = sender as UIElement;
|
||||
if (element == null) return;
|
||||
|
||||
// Скрываем визуальную обратную связь
|
||||
ShowVisualFeedback(element, false);
|
||||
|
||||
// Получаем данные
|
||||
var data = ExtractData(e.DataView);
|
||||
|
||||
// Получаем обработчик или используем встроенный
|
||||
var handler = GetDropHandler(element);
|
||||
if (handler != null)
|
||||
{
|
||||
// Создаем DropInfo для обработчика
|
||||
var dropInfo = CreateDropInfo(element, e, data);
|
||||
handler.Drop(dropInfo);
|
||||
}
|
||||
|
||||
// Вызываем пользовательский обработчик
|
||||
var actionHandler = GetDropHandlerAction(element);
|
||||
if (actionHandler != null && data != null)
|
||||
{
|
||||
actionHandler.Invoke(element, data);
|
||||
}
|
||||
|
||||
// Удаляем из словаря
|
||||
_dragOverElements.Remove(element);
|
||||
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
private static bool CanAcceptData(UIElement element, Windows.ApplicationModel.DataTransfer.DataPackageView dataView)
|
||||
{
|
||||
// Проверяем фильтр типов данных
|
||||
var acceptedTypes = GetAcceptsDataTypes(element);
|
||||
if (acceptedTypes != null && acceptedTypes.Length > 0)
|
||||
{
|
||||
// В реальной реализации нужно проверять доступные форматы данных
|
||||
// Здесь упрощенная проверка
|
||||
return dataView.AvailableFormats.Count > 0;
|
||||
}
|
||||
|
||||
// Если нет фильтра, принимаем все
|
||||
return true;
|
||||
}
|
||||
|
||||
private static object? ExtractData(Windows.ApplicationModel.DataTransfer.DataPackageView dataView)
|
||||
{
|
||||
// Упрощенная реализация извлечения данных
|
||||
// В реальном приложении нужно обрабатывать разные форматы данных
|
||||
try
|
||||
{
|
||||
if (dataView.Contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.Text))
|
||||
{
|
||||
// В WinUI 3 нужно использовать async/await, но это упрощенный пример
|
||||
// В реальном коде нужно использовать async методы
|
||||
return "Text data from drag";
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Игнорируем ошибки извлечения данных
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void ShowVisualFeedback(UIElement element, bool show)
|
||||
{
|
||||
if (!GetShowVisualFeedback(element)) return;
|
||||
|
||||
// Для элементов, которые являются Control, используем VisualStateManager
|
||||
if (element is Control control)
|
||||
{
|
||||
// Пытаемся перейти к состоянию "DragOver" или "Normal"
|
||||
try
|
||||
{
|
||||
VisualStateManager.GoToState(control, show ? "DragOver" : "Normal", true);
|
||||
// Получаем корневой элемент окна
|
||||
var rootVisual = element.XamlRoot?.Content as UIElement;
|
||||
if (rootVisual == null)
|
||||
return Rect.Empty;
|
||||
|
||||
// Преобразуем границы элемента в координаты корневого элемента
|
||||
var transform = element.TransformToVisual(rootVisual);
|
||||
var position = transform.TransformPoint(new Windows.Foundation.Point(0, 0));
|
||||
|
||||
return new Rect(
|
||||
position.X,
|
||||
position.Y,
|
||||
element.ActualWidth,
|
||||
element.ActualHeight);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Если состояния не определены, меняем свойства напрямую
|
||||
control.Background = show ?
|
||||
new Microsoft.UI.Xaml.Media.SolidColorBrush(Windows.UI.Color.FromArgb(30, 0, 120, 215)) :
|
||||
null;
|
||||
// В случае ошибки возвращаем пустой прямоугольник
|
||||
return Rect.Empty;
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
/// <summary>
|
||||
/// Определяет, может ли элемент принять сбрасываемые данные.
|
||||
/// </summary>
|
||||
/// <param name="dropInfo">Информация о сбросе.</param>
|
||||
/// <returns>
|
||||
/// true, если элемент может принять данные; в противном случае — false.
|
||||
/// </returns>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Этот метод является абстрактным и должен быть переопределен в производных классах
|
||||
/// для реализации логики принятия данных.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Базовая реализация всегда возвращает false. Переопределите этот метод, чтобы определить,
|
||||
/// какие типы данных может принимать ваш элемент и при каких условиях.
|
||||
/// </para>
|
||||
/// <example>
|
||||
/// Пример реализации:
|
||||
/// <code>
|
||||
/// public override bool CanAcceptDrop(DropInfo dropInfo)
|
||||
/// {
|
||||
/// // Принимаем только строковые данные
|
||||
/// return dropInfo.Data is string;
|
||||
/// }
|
||||
/// </code>
|
||||
/// </example>
|
||||
/// </remarks>
|
||||
public override async Task<bool> CanAcceptDropAsync(DropInfo dropInfo)
|
||||
{
|
||||
// Для обычных UIElement меняем свойства напрямую
|
||||
element.Opacity = show ? 0.8 : 1.0;
|
||||
// Базовая реализация - не принимает никакие данные.
|
||||
// Переопределите этот метод в производных классах.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static void UpdateVisualFeedback(UIElement element, Windows.Foundation.Point position)
|
||||
{
|
||||
// Можно добавить логику для различных зон сброса
|
||||
// Например, подсветка разных частей элемента
|
||||
}
|
||||
/// <summary>
|
||||
/// Обрабатывает сброс данных на элемент.
|
||||
/// </summary>
|
||||
/// <param name="dropInfo">Информация о сбросе.</param>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Этот метод вызывается, когда пользователь отпускает кнопку мыши над элементом,
|
||||
/// и данные должны быть приняты.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Базовая реализация ничего не делает. Переопределите этот метод, чтобы реализовать
|
||||
/// логику обработки принятых данных.
|
||||
/// </para>
|
||||
/// <example>
|
||||
/// Пример реализации:
|
||||
/// <code>
|
||||
/// public override void Drop(DropInfo dropInfo)
|
||||
/// {
|
||||
/// if (dropInfo.Data is string text)
|
||||
/// {
|
||||
/// // Обработка текстовых данных
|
||||
/// AssociatedElement.SetValue(TextBlock.TextProperty, text);
|
||||
/// dropInfo.MarkAsHandled();
|
||||
/// }
|
||||
/// }
|
||||
/// </code>
|
||||
/// </example>
|
||||
/// </remarks>
|
||||
public override async Task DropAsync(DropInfo dropInfo)
|
||||
{
|
||||
// Базовая реализация ничего не делает.
|
||||
// Переопределите этот метод в производных классах.
|
||||
}
|
||||
|
||||
private static Core.DragDrop.Models.DropInfo CreateDropInfo(UIElement element, DragEventArgs e, object? data)
|
||||
{
|
||||
var position = e.GetPosition(element);
|
||||
var screenPosition = element.TransformToVisual(null).TransformPoint(position);
|
||||
/// <summary>
|
||||
/// Освобождает ресурсы, связанные с поведением.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Этот метод отписывается от всех событий, отменяет регистрацию в сервисе перетаскивания
|
||||
/// и очищает все ресурсы.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// После вызова этого метода поведение больше не может быть использовано.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public override void Detach()
|
||||
{
|
||||
if (AssociatedElement != null && _attachedBehaviors.TryGetValue(AssociatedElement, out _))
|
||||
{
|
||||
_attachedBehaviors.TryRemove(AssociatedElement, out _);
|
||||
}
|
||||
|
||||
return new Core.DragDrop.Models.DropInfo(
|
||||
data: data,
|
||||
position: new Core.Geometry.Point(screenPosition.X, screenPosition.Y),
|
||||
allowedEffects: Core.DragDrop.Enums.DragDropEffects.Copy | Core.DragDrop.Enums.DragDropEffects.Move,
|
||||
target: GetDropHandler(element)
|
||||
);
|
||||
base.Detach();
|
||||
}
|
||||
|
||||
#region Event Handlers
|
||||
|
||||
private void OnLayoutUpdated(object? sender, object e)
|
||||
{
|
||||
OnElementLayoutChanged();
|
||||
}
|
||||
|
||||
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
|
||||
{
|
||||
OnElementLayoutChanged();
|
||||
}
|
||||
|
||||
private void OnLoaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
UpdateBounds();
|
||||
}
|
||||
|
||||
private static void OnElementUnloaded(object sender, RoutedEventArgs e)
|
||||
{
|
||||
if (sender is FrameworkElement element)
|
||||
{
|
||||
Detach(element);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user