ItemDragBehavior.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. using System;
  2. using System.Collections;
  3. using Avalonia.Controls;
  4. using Avalonia.Controls.Primitives;
  5. using Avalonia.Input;
  6. using Avalonia.Interactivity;
  7. using Avalonia.Layout;
  8. using Avalonia.Media.Transformation;
  9. using Avalonia.Xaml.Interactivity;
  10. namespace Avalonia.Xaml.Interactions.Draggable;
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. public class ItemDragBehavior : StyledElementBehavior<Control>
  15. {
  16. private bool _enableDrag;
  17. private bool _dragStarted;
  18. private Point _start;
  19. private int _draggedIndex;
  20. private int _targetIndex;
  21. private ItemsControl? _itemsControl;
  22. private Control? _draggedContainer;
  23. private bool _captured;
  24. /// <summary>
  25. ///
  26. /// </summary>
  27. public static readonly StyledProperty<Orientation> OrientationProperty =
  28. AvaloniaProperty.Register<ItemDragBehavior, Orientation>(nameof(Orientation));
  29. /// <summary>
  30. ///
  31. /// </summary>
  32. public static readonly StyledProperty<double> HorizontalDragThresholdProperty =
  33. AvaloniaProperty.Register<ItemDragBehavior, double>(nameof(HorizontalDragThreshold), 3);
  34. /// <summary>
  35. ///
  36. /// </summary>
  37. public static readonly StyledProperty<double> VerticalDragThresholdProperty =
  38. AvaloniaProperty.Register<ItemDragBehavior, double>(nameof(VerticalDragThreshold), 3);
  39. /// <summary>
  40. ///
  41. /// </summary>
  42. public Orientation Orientation
  43. {
  44. get => GetValue(OrientationProperty);
  45. set => SetValue(OrientationProperty, value);
  46. }
  47. /// <summary>
  48. ///
  49. /// </summary>
  50. public double HorizontalDragThreshold
  51. {
  52. get => GetValue(HorizontalDragThresholdProperty);
  53. set => SetValue(HorizontalDragThresholdProperty, value);
  54. }
  55. /// <summary>
  56. ///
  57. /// </summary>
  58. public double VerticalDragThreshold
  59. {
  60. get => GetValue(VerticalDragThresholdProperty);
  61. set => SetValue(VerticalDragThresholdProperty, value);
  62. }
  63. /// <inheritdoc />
  64. protected override void OnAttachedToVisualTree()
  65. {
  66. if (AssociatedObject is not null)
  67. {
  68. AssociatedObject.AddHandler(InputElement.PointerReleasedEvent, PointerReleased, RoutingStrategies.Tunnel);
  69. AssociatedObject.AddHandler(InputElement.PointerPressedEvent, PointerPressed, RoutingStrategies.Tunnel);
  70. AssociatedObject.AddHandler(InputElement.PointerMovedEvent, PointerMoved, RoutingStrategies.Tunnel);
  71. AssociatedObject.AddHandler(InputElement.PointerCaptureLostEvent, PointerCaptureLost, RoutingStrategies.Tunnel);
  72. }
  73. }
  74. /// <inheritdoc />
  75. protected override void OnDetachedFromVisualTree()
  76. {
  77. if (AssociatedObject is not null)
  78. {
  79. AssociatedObject.RemoveHandler(InputElement.PointerReleasedEvent, PointerReleased);
  80. AssociatedObject.RemoveHandler(InputElement.PointerPressedEvent, PointerPressed);
  81. AssociatedObject.RemoveHandler(InputElement.PointerMovedEvent, PointerMoved);
  82. AssociatedObject.RemoveHandler(InputElement.PointerCaptureLostEvent, PointerCaptureLost);
  83. }
  84. }
  85. private void PointerPressed(object? sender, PointerPressedEventArgs e)
  86. {
  87. var properties = e.GetCurrentPoint(AssociatedObject).Properties;
  88. if (properties.IsLeftButtonPressed
  89. && AssociatedObject?.Parent is ItemsControl itemsControl)
  90. {
  91. _enableDrag = true;
  92. _dragStarted = false;
  93. _start = e.GetPosition(itemsControl);
  94. _draggedIndex = -1;
  95. _targetIndex = -1;
  96. _itemsControl = itemsControl;
  97. _draggedContainer = AssociatedObject;
  98. if (_draggedContainer is not null)
  99. {
  100. SetDraggingPseudoClasses(_draggedContainer, true);
  101. }
  102. AddTransforms(_itemsControl);
  103. _captured = true;
  104. }
  105. }
  106. private void PointerReleased(object? sender, PointerReleasedEventArgs e)
  107. {
  108. if (_captured)
  109. {
  110. if (e.InitialPressMouseButton == MouseButton.Left)
  111. {
  112. Released();
  113. }
  114. _captured = false;
  115. }
  116. }
  117. private void PointerCaptureLost(object? sender, PointerCaptureLostEventArgs e)
  118. {
  119. Released();
  120. _captured = false;
  121. }
  122. private void Released()
  123. {
  124. if (!_enableDrag)
  125. {
  126. return;
  127. }
  128. RemoveTransforms(_itemsControl);
  129. if (_itemsControl is not null)
  130. {
  131. foreach (var control in _itemsControl.GetRealizedContainers())
  132. {
  133. SetDraggingPseudoClasses(control, true);
  134. }
  135. }
  136. if (_dragStarted)
  137. {
  138. if (_draggedIndex >= 0 && _targetIndex >= 0 && _draggedIndex != _targetIndex)
  139. {
  140. MoveDraggedItem(_itemsControl, _draggedIndex, _targetIndex);
  141. }
  142. }
  143. if (_itemsControl is not null)
  144. {
  145. foreach (var control in _itemsControl.GetRealizedContainers())
  146. {
  147. SetDraggingPseudoClasses(control, false);
  148. }
  149. }
  150. if (_draggedContainer is not null)
  151. {
  152. SetDraggingPseudoClasses(_draggedContainer, false);
  153. }
  154. _draggedIndex = -1;
  155. _targetIndex = -1;
  156. _enableDrag = false;
  157. _dragStarted = false;
  158. _itemsControl = null;
  159. _draggedContainer = null;
  160. }
  161. private void AddTransforms(ItemsControl? itemsControl)
  162. {
  163. if (itemsControl?.Items is null)
  164. {
  165. return;
  166. }
  167. var i = 0;
  168. foreach (var _ in itemsControl.Items)
  169. {
  170. var container = itemsControl.ContainerFromIndex(i);
  171. if (container is not null)
  172. {
  173. SetTranslateTransform(container, 0, 0);
  174. }
  175. i++;
  176. }
  177. }
  178. private void RemoveTransforms(ItemsControl? itemsControl)
  179. {
  180. if (itemsControl?.Items is null)
  181. {
  182. return;
  183. }
  184. var i = 0;
  185. foreach (var _ in itemsControl.Items)
  186. {
  187. var container = itemsControl.ContainerFromIndex(i);
  188. if (container is not null)
  189. {
  190. SetTranslateTransform(container, 0, 0);
  191. }
  192. i++;
  193. }
  194. }
  195. private void MoveDraggedItem(ItemsControl? itemsControl, int draggedIndex, int targetIndex)
  196. {
  197. if (itemsControl?.ItemsSource is IList itemsSource)
  198. {
  199. var draggedItem = itemsSource[draggedIndex];
  200. itemsSource.RemoveAt(draggedIndex);
  201. itemsSource.Insert(targetIndex, draggedItem);
  202. if (itemsControl is SelectingItemsControl selectingItemsControl)
  203. {
  204. selectingItemsControl.SelectedIndex = targetIndex;
  205. }
  206. }
  207. else
  208. {
  209. if (itemsControl?.Items is {IsReadOnly: false} itemCollection)
  210. {
  211. var draggedItem = itemCollection[draggedIndex];
  212. itemCollection.RemoveAt(draggedIndex);
  213. itemCollection.Insert(targetIndex, draggedItem);
  214. if (itemsControl is SelectingItemsControl selectingItemsControl)
  215. {
  216. selectingItemsControl.SelectedIndex = targetIndex;
  217. }
  218. }
  219. }
  220. }
  221. private void PointerMoved(object? sender, PointerEventArgs e)
  222. {
  223. var properties = e.GetCurrentPoint(AssociatedObject).Properties;
  224. if (_captured
  225. && properties.IsLeftButtonPressed)
  226. {
  227. if (_itemsControl?.Items is null || _draggedContainer?.RenderTransform is null || !_enableDrag)
  228. {
  229. return;
  230. }
  231. var orientation = Orientation;
  232. var position = e.GetPosition(_itemsControl);
  233. var delta = orientation == Orientation.Horizontal ? position.X - _start.X : position.Y - _start.Y;
  234. if (!_dragStarted)
  235. {
  236. var diff = _start - position;
  237. var horizontalDragThreshold = HorizontalDragThreshold;
  238. var verticalDragThreshold = VerticalDragThreshold;
  239. if (orientation == Orientation.Horizontal)
  240. {
  241. if (Math.Abs(diff.X) > horizontalDragThreshold)
  242. {
  243. _dragStarted = true;
  244. }
  245. else
  246. {
  247. return;
  248. }
  249. }
  250. else
  251. {
  252. if (Math.Abs(diff.Y) > verticalDragThreshold)
  253. {
  254. _dragStarted = true;
  255. }
  256. else
  257. {
  258. return;
  259. }
  260. }
  261. }
  262. if (orientation == Orientation.Horizontal)
  263. {
  264. SetTranslateTransform(_draggedContainer, delta, 0);
  265. }
  266. else
  267. {
  268. SetTranslateTransform(_draggedContainer, 0, delta);
  269. }
  270. _draggedIndex = _itemsControl.IndexFromContainer(_draggedContainer);
  271. _targetIndex = -1;
  272. var draggedBounds = _draggedContainer.Bounds;
  273. var draggedStart = orientation == Orientation.Horizontal ? draggedBounds.X : draggedBounds.Y;
  274. var draggedDeltaStart = orientation == Orientation.Horizontal
  275. ? draggedBounds.X + delta
  276. : draggedBounds.Y + delta;
  277. var draggedDeltaEnd = orientation == Orientation.Horizontal
  278. ? draggedBounds.X + delta + draggedBounds.Width
  279. : draggedBounds.Y + delta + draggedBounds.Height;
  280. var i = 0;
  281. foreach (var _ in _itemsControl.Items)
  282. {
  283. var targetContainer = _itemsControl.ContainerFromIndex(i);
  284. if (targetContainer?.RenderTransform is null || ReferenceEquals(targetContainer, _draggedContainer))
  285. {
  286. i++;
  287. continue;
  288. }
  289. var targetBounds = targetContainer.Bounds;
  290. var targetStart = orientation == Orientation.Horizontal ? targetBounds.X : targetBounds.Y;
  291. var targetMid = orientation == Orientation.Horizontal
  292. ? targetBounds.X + targetBounds.Width / 2
  293. : targetBounds.Y + targetBounds.Height / 2;
  294. var targetIndex = _itemsControl.IndexFromContainer(targetContainer);
  295. if (targetStart > draggedStart && draggedDeltaEnd >= targetMid)
  296. {
  297. if (orientation == Orientation.Horizontal)
  298. {
  299. SetTranslateTransform(targetContainer, -draggedBounds.Width, 0);
  300. }
  301. else
  302. {
  303. SetTranslateTransform(targetContainer, 0, -draggedBounds.Height);
  304. }
  305. _targetIndex = _targetIndex == -1 ? targetIndex :
  306. targetIndex > _targetIndex ? targetIndex : _targetIndex;
  307. }
  308. else if (targetStart < draggedStart && draggedDeltaStart <= targetMid)
  309. {
  310. if (orientation == Orientation.Horizontal)
  311. {
  312. SetTranslateTransform(targetContainer, draggedBounds.Width, 0);
  313. }
  314. else
  315. {
  316. SetTranslateTransform(targetContainer, 0, draggedBounds.Height);
  317. }
  318. _targetIndex = _targetIndex == -1 ? targetIndex :
  319. targetIndex < _targetIndex ? targetIndex : _targetIndex;
  320. }
  321. else
  322. {
  323. if (orientation == Orientation.Horizontal)
  324. {
  325. SetTranslateTransform(targetContainer, 0, 0);
  326. }
  327. else
  328. {
  329. SetTranslateTransform(targetContainer, 0, 0);
  330. }
  331. }
  332. i++;
  333. }
  334. }
  335. }
  336. private void SetDraggingPseudoClasses(Control control, bool isDragging)
  337. {
  338. if (isDragging)
  339. {
  340. ((IPseudoClasses)control.Classes).Add(":dragging");
  341. }
  342. else
  343. {
  344. ((IPseudoClasses)control.Classes).Remove(":dragging");
  345. }
  346. }
  347. private void SetTranslateTransform(Control control, double x, double y)
  348. {
  349. var transformBuilder = new TransformOperations.Builder(1);
  350. transformBuilder.AppendTranslate(x, y);
  351. control.RenderTransform = transformBuilder.Build();
  352. }
  353. }