SelectingItemsControl.cs 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.Linq;
  7. using Avalonia.Controls.Generators;
  8. using Avalonia.Controls.Selection;
  9. using Avalonia.Data;
  10. using Avalonia.Input;
  11. using Avalonia.Input.Platform;
  12. using Avalonia.Interactivity;
  13. using Avalonia.VisualTree;
  14. #nullable enable
  15. namespace Avalonia.Controls.Primitives
  16. {
  17. /// <summary>
  18. /// An <see cref="ItemsControl"/> that maintains a selection.
  19. /// </summary>
  20. /// <remarks>
  21. /// <para>
  22. /// <see cref="SelectingItemsControl"/> provides a base class for <see cref="ItemsControl"/>s
  23. /// that maintain a selection (single or multiple). By default only its
  24. /// <see cref="SelectedIndex"/> and <see cref="SelectedItem"/> properties are visible; the
  25. /// current multiple <see cref="Selection"/> and <see cref="SelectedItems"/> together with the
  26. /// <see cref="SelectionMode"/> properties are protected, however a derived class can expose
  27. /// these if it wishes to support multiple selection.
  28. /// </para>
  29. /// <para>
  30. /// <see cref="SelectingItemsControl"/> maintains a selection respecting the current
  31. /// <see cref="SelectionMode"/> but it does not react to user input; this must be handled in a
  32. /// derived class. It does, however, respond to <see cref="IsSelectedChangedEvent"/> events
  33. /// from items and updates the selection accordingly.
  34. /// </para>
  35. /// </remarks>
  36. public class SelectingItemsControl : ItemsControl
  37. {
  38. /// <summary>
  39. /// Defines the <see cref="AutoScrollToSelectedItem"/> property.
  40. /// </summary>
  41. public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty =
  42. AvaloniaProperty.Register<SelectingItemsControl, bool>(
  43. nameof(AutoScrollToSelectedItem),
  44. defaultValue: true);
  45. /// <summary>
  46. /// Defines the <see cref="SelectedIndex"/> property.
  47. /// </summary>
  48. public static readonly DirectProperty<SelectingItemsControl, int> SelectedIndexProperty =
  49. AvaloniaProperty.RegisterDirect<SelectingItemsControl, int>(
  50. nameof(SelectedIndex),
  51. o => o.SelectedIndex,
  52. (o, v) => o.SelectedIndex = v,
  53. unsetValue: -1,
  54. defaultBindingMode: BindingMode.TwoWay);
  55. /// <summary>
  56. /// Defines the <see cref="SelectedItem"/> property.
  57. /// </summary>
  58. public static readonly DirectProperty<SelectingItemsControl, object?> SelectedItemProperty =
  59. AvaloniaProperty.RegisterDirect<SelectingItemsControl, object?>(
  60. nameof(SelectedItem),
  61. o => o.SelectedItem,
  62. (o, v) => o.SelectedItem = v,
  63. defaultBindingMode: BindingMode.TwoWay, enableDataValidation: true);
  64. /// <summary>
  65. /// Defines the <see cref="SelectedItems"/> property.
  66. /// </summary>
  67. protected static readonly DirectProperty<SelectingItemsControl, IList?> SelectedItemsProperty =
  68. AvaloniaProperty.RegisterDirect<SelectingItemsControl, IList?>(
  69. nameof(SelectedItems),
  70. o => o.SelectedItems,
  71. (o, v) => o.SelectedItems = v);
  72. /// <summary>
  73. /// Defines the <see cref="Selection"/> property.
  74. /// </summary>
  75. protected static readonly DirectProperty<SelectingItemsControl, ISelectionModel> SelectionProperty =
  76. AvaloniaProperty.RegisterDirect<SelectingItemsControl, ISelectionModel>(
  77. nameof(Selection),
  78. o => o.Selection,
  79. (o, v) => o.Selection = v);
  80. /// <summary>
  81. /// Defines the <see cref="SelectionMode"/> property.
  82. /// </summary>
  83. protected static readonly StyledProperty<SelectionMode> SelectionModeProperty =
  84. AvaloniaProperty.Register<SelectingItemsControl, SelectionMode>(
  85. nameof(SelectionMode));
  86. /// <summary>
  87. /// Event that should be raised by items that implement <see cref="ISelectable"/> to
  88. /// notify the parent <see cref="SelectingItemsControl"/> that their selection state
  89. /// has changed.
  90. /// </summary>
  91. public static readonly RoutedEvent<RoutedEventArgs> IsSelectedChangedEvent =
  92. RoutedEvent.Register<SelectingItemsControl, RoutedEventArgs>(
  93. "IsSelectedChanged",
  94. RoutingStrategies.Bubble);
  95. /// <summary>
  96. /// Defines the <see cref="SelectionChanged"/> event.
  97. /// </summary>
  98. public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent =
  99. RoutedEvent.Register<SelectingItemsControl, SelectionChangedEventArgs>(
  100. "SelectionChanged",
  101. RoutingStrategies.Bubble);
  102. private static readonly IList Empty = Array.Empty<object>();
  103. private ISelectionModel? _selection;
  104. private int _oldSelectedIndex;
  105. private object? _oldSelectedItem;
  106. private IList? _oldSelectedItems;
  107. private bool _ignoreContainerSelectionChanged;
  108. private UpdateState? _updateState;
  109. private bool _hasScrolledToSelectedItem;
  110. /// <summary>
  111. /// Initializes static members of the <see cref="SelectingItemsControl"/> class.
  112. /// </summary>
  113. static SelectingItemsControl()
  114. {
  115. IsSelectedChangedEvent.AddClassHandler<SelectingItemsControl>((x, e) => x.ContainerSelectionChanged(e));
  116. }
  117. /// <summary>
  118. /// Occurs when the control's selection changes.
  119. /// </summary>
  120. public event EventHandler<SelectionChangedEventArgs> SelectionChanged
  121. {
  122. add { AddHandler(SelectionChangedEvent, value); }
  123. remove { RemoveHandler(SelectionChangedEvent, value); }
  124. }
  125. /// <summary>
  126. /// Gets or sets a value indicating whether to automatically scroll to newly selected items.
  127. /// </summary>
  128. public bool AutoScrollToSelectedItem
  129. {
  130. get { return GetValue(AutoScrollToSelectedItemProperty); }
  131. set { SetValue(AutoScrollToSelectedItemProperty, value); }
  132. }
  133. /// <summary>
  134. /// Gets or sets the index of the selected item.
  135. /// </summary>
  136. public int SelectedIndex
  137. {
  138. get
  139. {
  140. // When a Begin/EndInit/DataContext update is in place we return the value to be
  141. // updated here, even though it's not yet active and the property changed notification
  142. // has not yet been raised. If we don't do this then the old value will be written back
  143. // to the source when two-way bound, and the update value will be lost.
  144. return _updateState?.SelectedIndex.HasValue == true ?
  145. _updateState.SelectedIndex.Value :
  146. Selection.SelectedIndex;
  147. }
  148. set
  149. {
  150. if (_updateState is object)
  151. {
  152. _updateState.SelectedIndex = value;
  153. }
  154. else
  155. {
  156. Selection.SelectedIndex = value;
  157. }
  158. }
  159. }
  160. /// <summary>
  161. /// Gets or sets the selected item.
  162. /// </summary>
  163. public object? SelectedItem
  164. {
  165. get
  166. {
  167. // See SelectedIndex setter for more information.
  168. return _updateState?.SelectedItem.HasValue == true ?
  169. _updateState.SelectedItem.Value :
  170. Selection.SelectedItem;
  171. }
  172. set
  173. {
  174. if (_updateState is object)
  175. {
  176. _updateState.SelectedItem = value;
  177. }
  178. else
  179. {
  180. Selection.SelectedItem = value;
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// Gets or sets the selected items.
  186. /// </summary>
  187. /// <remarks>
  188. /// By default returns a collection that can be modified in order to manipulate the control
  189. /// selection, however this property will return null if <see cref="Selection"/> is
  190. /// re-assigned; you should only use _either_ Selection or SelectedItems.
  191. /// </remarks>
  192. protected IList? SelectedItems
  193. {
  194. get
  195. {
  196. // See SelectedIndex setter for more information.
  197. if (_updateState?.SelectedItems.HasValue == true)
  198. {
  199. return _updateState.SelectedItems.Value;
  200. }
  201. else if (Selection is InternalSelectionModel ism)
  202. {
  203. var result = ism.WritableSelectedItems;
  204. _oldSelectedItems = result;
  205. return result;
  206. }
  207. return null;
  208. }
  209. set
  210. {
  211. if (_updateState is object)
  212. {
  213. _updateState.SelectedItems = new Optional<IList?>(value);
  214. }
  215. else if (Selection is InternalSelectionModel i)
  216. {
  217. i.WritableSelectedItems = value;
  218. }
  219. else
  220. {
  221. throw new InvalidOperationException("Cannot set both Selection and SelectedItems.");
  222. }
  223. }
  224. }
  225. /// <summary>
  226. /// Gets or sets the model that holds the current selection.
  227. /// </summary>
  228. protected ISelectionModel Selection
  229. {
  230. get
  231. {
  232. if (_updateState?.Selection.HasValue == true)
  233. {
  234. return _updateState.Selection.Value;
  235. }
  236. else
  237. {
  238. if (_selection is null)
  239. {
  240. _selection = CreateDefaultSelectionModel();
  241. InitializeSelectionModel(_selection);
  242. }
  243. return _selection;
  244. }
  245. }
  246. set
  247. {
  248. value ??= CreateDefaultSelectionModel();
  249. if (_updateState is object)
  250. {
  251. _updateState.Selection = new Optional<ISelectionModel>(value);
  252. }
  253. else if (_selection != value)
  254. {
  255. if (value.Source != null && value.Source != Items)
  256. {
  257. throw new ArgumentException(
  258. "The supplied ISelectionModel already has an assigned Source but this " +
  259. "collection is different to the Items on the control.");
  260. }
  261. var oldSelection = _selection?.SelectedItems.ToList();
  262. DeinitializeSelectionModel(_selection);
  263. _selection = value;
  264. if (oldSelection?.Count > 0)
  265. {
  266. RaiseEvent(new SelectionChangedEventArgs(
  267. SelectionChangedEvent,
  268. oldSelection,
  269. Array.Empty<object>()));
  270. }
  271. InitializeSelectionModel(_selection);
  272. if (_oldSelectedItems != SelectedItems)
  273. {
  274. RaisePropertyChanged(
  275. SelectedItemsProperty,
  276. new Optional<IList?>(_oldSelectedItems),
  277. new BindingValue<IList?>(SelectedItems));
  278. _oldSelectedItems = SelectedItems;
  279. }
  280. }
  281. }
  282. }
  283. /// <summary>
  284. /// Gets or sets the selection mode.
  285. /// </summary>
  286. /// <remarks>
  287. /// Note that the selection mode only applies to selections made via user interaction.
  288. /// Multiple selections can be made programatically regardless of the value of this property.
  289. /// </remarks>
  290. protected SelectionMode SelectionMode
  291. {
  292. get { return GetValue(SelectionModeProperty); }
  293. set { SetValue(SelectionModeProperty, value); }
  294. }
  295. /// <summary>
  296. /// Gets a value indicating whether <see cref="SelectionMode.AlwaysSelected"/> is set.
  297. /// </summary>
  298. protected bool AlwaysSelected => SelectionMode.HasFlagCustom(SelectionMode.AlwaysSelected);
  299. /// <inheritdoc/>
  300. public override void BeginInit()
  301. {
  302. base.BeginInit();
  303. BeginUpdating();
  304. }
  305. /// <inheritdoc/>
  306. public override void EndInit()
  307. {
  308. base.EndInit();
  309. EndUpdating();
  310. }
  311. /// <summary>
  312. /// Scrolls the specified item into view.
  313. /// </summary>
  314. /// <param name="index">The index of the item.</param>
  315. public void ScrollIntoView(int index) => Presenter?.ScrollIntoView(index);
  316. /// <summary>
  317. /// Scrolls the specified item into view.
  318. /// </summary>
  319. /// <param name="item">The item.</param>
  320. public void ScrollIntoView(object item) => ScrollIntoView(IndexOf(Items, item));
  321. /// <summary>
  322. /// Tries to get the container that was the source of an event.
  323. /// </summary>
  324. /// <param name="eventSource">The control that raised the event.</param>
  325. /// <returns>The container or null if the event did not originate in a container.</returns>
  326. protected IControl? GetContainerFromEventSource(IInteractive? eventSource)
  327. {
  328. for (var current = eventSource as IVisual; current != null; current = current.VisualParent)
  329. {
  330. if (current is IControl control && control.LogicalParent == this &&
  331. ItemContainerGenerator?.IndexFromContainer(control) != -1)
  332. {
  333. return control;
  334. }
  335. }
  336. return null;
  337. }
  338. protected override void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  339. {
  340. base.ItemsCollectionChanged(sender, e);
  341. if (AlwaysSelected && SelectedIndex == -1 && ItemCount > 0)
  342. {
  343. SelectedIndex = 0;
  344. }
  345. }
  346. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  347. {
  348. base.OnAttachedToVisualTree(e);
  349. AutoScrollToSelectedItemIfNecessary();
  350. }
  351. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  352. {
  353. base.OnApplyTemplate(e);
  354. void ExecuteScrollWhenLayoutUpdated(object sender, EventArgs e)
  355. {
  356. LayoutUpdated -= ExecuteScrollWhenLayoutUpdated;
  357. AutoScrollToSelectedItemIfNecessary();
  358. }
  359. if (AutoScrollToSelectedItem)
  360. {
  361. LayoutUpdated += ExecuteScrollWhenLayoutUpdated;
  362. }
  363. }
  364. /// <inheritdoc/>
  365. protected override void OnContainersMaterialized(ItemContainerEventArgs e)
  366. {
  367. base.OnContainersMaterialized(e);
  368. foreach (var container in e.Containers)
  369. {
  370. if ((container.ContainerControl as ISelectable)?.IsSelected == true)
  371. {
  372. Selection.Select(container.Index);
  373. MarkContainerSelected(container.ContainerControl, true);
  374. }
  375. else
  376. {
  377. var selected = Selection.IsSelected(container.Index);
  378. MarkContainerSelected(container.ContainerControl, selected);
  379. }
  380. }
  381. }
  382. /// <inheritdoc/>
  383. protected override void OnContainersDematerialized(ItemContainerEventArgs e)
  384. {
  385. base.OnContainersDematerialized(e);
  386. var panel = (InputElement)Presenter.Panel;
  387. if (panel != null)
  388. {
  389. foreach (var container in e.Containers)
  390. {
  391. if (KeyboardNavigation.GetTabOnceActiveElement(panel) == container.ContainerControl)
  392. {
  393. KeyboardNavigation.SetTabOnceActiveElement(panel, null);
  394. break;
  395. }
  396. }
  397. }
  398. }
  399. protected override void OnContainersRecycled(ItemContainerEventArgs e)
  400. {
  401. foreach (var i in e.Containers)
  402. {
  403. if (i.ContainerControl != null && i.Item != null)
  404. {
  405. bool selected = Selection.IsSelected(i.Index);
  406. MarkContainerSelected(i.ContainerControl, selected);
  407. }
  408. }
  409. }
  410. /// <inheritdoc/>
  411. protected override void OnDataContextBeginUpdate()
  412. {
  413. base.OnDataContextBeginUpdate();
  414. BeginUpdating();
  415. }
  416. /// <inheritdoc/>
  417. protected override void OnDataContextEndUpdate()
  418. {
  419. base.OnDataContextEndUpdate();
  420. EndUpdating();
  421. }
  422. /// <summary>
  423. /// Called to update the validation state for properties for which data validation is
  424. /// enabled.
  425. /// </summary>
  426. /// <param name="property">The property.</param>
  427. /// <param name="value">The new binding value for the property.</param>
  428. protected override void UpdateDataValidation<T>(AvaloniaProperty<T> property, BindingValue<T> value)
  429. {
  430. if (property == SelectedItemProperty)
  431. {
  432. DataValidationErrors.SetError(this, value.Error);
  433. }
  434. }
  435. protected override void OnInitialized()
  436. {
  437. base.OnInitialized();
  438. if (_selection is object)
  439. {
  440. _selection.Source = Items;
  441. }
  442. }
  443. protected override void OnKeyDown(KeyEventArgs e)
  444. {
  445. base.OnKeyDown(e);
  446. if (!e.Handled)
  447. {
  448. var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
  449. bool Match(List<KeyGesture> gestures) => gestures.Any(g => g.Matches(e));
  450. if (ItemCount > 0 &&
  451. Match(keymap.SelectAll) &&
  452. SelectionMode.HasFlagCustom(SelectionMode.Multiple))
  453. {
  454. Selection.SelectAll();
  455. e.Handled = true;
  456. }
  457. }
  458. }
  459. protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
  460. {
  461. base.OnPropertyChanged(change);
  462. if (change.Property == AutoScrollToSelectedItemProperty)
  463. {
  464. AutoScrollToSelectedItemIfNecessary();
  465. }
  466. if (change.Property == ItemsProperty && _updateState is null && _selection is object)
  467. {
  468. var newValue = change.NewValue.GetValueOrDefault<IEnumerable>();
  469. _selection.Source = newValue;
  470. if (newValue is null)
  471. {
  472. _selection.Clear();
  473. }
  474. }
  475. else if (change.Property == SelectionModeProperty && _selection is object)
  476. {
  477. var newValue = change.NewValue.GetValueOrDefault<SelectionMode>();
  478. _selection.SingleSelect = !newValue.HasFlagCustom(SelectionMode.Multiple);
  479. }
  480. }
  481. /// <summary>
  482. /// Moves the selection in the specified direction relative to the current selection.
  483. /// </summary>
  484. /// <param name="direction">The direction to move.</param>
  485. /// <param name="wrap">Whether to wrap when the selection reaches the first or last item.</param>
  486. /// <returns>True if the selection was moved; otherwise false.</returns>
  487. protected bool MoveSelection(NavigationDirection direction, bool wrap)
  488. {
  489. var from = SelectedIndex != -1 ? ItemContainerGenerator.ContainerFromIndex(SelectedIndex) : null;
  490. return MoveSelection(from, direction, wrap);
  491. }
  492. /// <summary>
  493. /// Moves the selection in the specified direction relative to the specified container.
  494. /// </summary>
  495. /// <param name="from">The container which serves as a starting point for the movement.</param>
  496. /// <param name="direction">The direction to move.</param>
  497. /// <param name="wrap">Whether to wrap when the selection reaches the first or last item.</param>
  498. /// <returns>True if the selection was moved; otherwise false.</returns>
  499. protected bool MoveSelection(IControl? from, NavigationDirection direction, bool wrap)
  500. {
  501. if (Presenter?.Panel is INavigableContainer container &&
  502. GetNextControl(container, direction, from, wrap) is IControl next)
  503. {
  504. var index = ItemContainerGenerator.IndexFromContainer(next);
  505. if (index != -1)
  506. {
  507. SelectedIndex = index;
  508. return true;
  509. }
  510. }
  511. return false;
  512. }
  513. /// <summary>
  514. /// Updates the selection for an item based on user interaction.
  515. /// </summary>
  516. /// <param name="index">The index of the item.</param>
  517. /// <param name="select">Whether the item should be selected or unselected.</param>
  518. /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
  519. /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
  520. /// <param name="rightButton">Whether the event is a right-click.</param>
  521. protected void UpdateSelection(
  522. int index,
  523. bool select = true,
  524. bool rangeModifier = false,
  525. bool toggleModifier = false,
  526. bool rightButton = false)
  527. {
  528. if (index < 0 || index >= ItemCount)
  529. {
  530. return;
  531. }
  532. var mode = SelectionMode;
  533. var multi = mode.HasFlagCustom(SelectionMode.Multiple);
  534. var toggle = toggleModifier || mode.HasFlagCustom(SelectionMode.Toggle);
  535. var range = multi && rangeModifier;
  536. if (!select)
  537. {
  538. Selection.Deselect(index);
  539. }
  540. else if (rightButton)
  541. {
  542. if (Selection.IsSelected(index) == false)
  543. {
  544. SelectedIndex = index;
  545. }
  546. }
  547. else if (range)
  548. {
  549. using var operation = Selection.BatchUpdate();
  550. Selection.Clear();
  551. Selection.SelectRange(Selection.AnchorIndex, index);
  552. }
  553. else if (multi && toggle)
  554. {
  555. if (Selection.IsSelected(index) == true)
  556. {
  557. Selection.Deselect(index);
  558. }
  559. else
  560. {
  561. Selection.Select(index);
  562. }
  563. }
  564. else if (toggle)
  565. {
  566. SelectedIndex = (SelectedIndex == index) ? -1 : index;
  567. }
  568. else
  569. {
  570. using var operation = Selection.BatchUpdate();
  571. Selection.Clear();
  572. Selection.Select(index);
  573. }
  574. if (Presenter?.Panel != null)
  575. {
  576. var container = ItemContainerGenerator.ContainerFromIndex(index);
  577. KeyboardNavigation.SetTabOnceActiveElement(
  578. (InputElement)Presenter.Panel,
  579. container);
  580. }
  581. }
  582. /// <summary>
  583. /// Updates the selection for a container based on user interaction.
  584. /// </summary>
  585. /// <param name="container">The container.</param>
  586. /// <param name="select">Whether the container should be selected or unselected.</param>
  587. /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
  588. /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
  589. /// <param name="rightButton">Whether the event is a right-click.</param>
  590. protected void UpdateSelection(
  591. IControl container,
  592. bool select = true,
  593. bool rangeModifier = false,
  594. bool toggleModifier = false,
  595. bool rightButton = false)
  596. {
  597. var index = ItemContainerGenerator?.IndexFromContainer(container) ?? -1;
  598. if (index != -1)
  599. {
  600. UpdateSelection(index, select, rangeModifier, toggleModifier, rightButton);
  601. }
  602. }
  603. /// <summary>
  604. /// Updates the selection based on an event that may have originated in a container that
  605. /// belongs to the control.
  606. /// </summary>
  607. /// <param name="eventSource">The control that raised the event.</param>
  608. /// <param name="select">Whether the container should be selected or unselected.</param>
  609. /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
  610. /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
  611. /// <param name="rightButton">Whether the event is a right-click.</param>
  612. /// <returns>
  613. /// True if the event originated from a container that belongs to the control; otherwise
  614. /// false.
  615. /// </returns>
  616. protected bool UpdateSelectionFromEventSource(
  617. IInteractive? eventSource,
  618. bool select = true,
  619. bool rangeModifier = false,
  620. bool toggleModifier = false,
  621. bool rightButton = false)
  622. {
  623. var container = GetContainerFromEventSource(eventSource);
  624. if (container != null)
  625. {
  626. UpdateSelection(container, select, rangeModifier, toggleModifier, rightButton);
  627. return true;
  628. }
  629. return false;
  630. }
  631. /// <summary>
  632. /// Called when <see cref="INotifyPropertyChanged.PropertyChanged"/> is raised on
  633. /// <see cref="Selection"/>.
  634. /// </summary>
  635. /// <param name="sender">The sender.</param>
  636. /// <param name="e">The event args.</param>
  637. private void OnSelectionModelPropertyChanged(object sender, PropertyChangedEventArgs e)
  638. {
  639. if (e.PropertyName == nameof(ISelectionModel.AnchorIndex))
  640. {
  641. _hasScrolledToSelectedItem = false;
  642. AutoScrollToSelectedItemIfNecessary();
  643. }
  644. else if (e.PropertyName == nameof(ISelectionModel.SelectedIndex) && _oldSelectedIndex != SelectedIndex)
  645. {
  646. RaisePropertyChanged(SelectedIndexProperty, _oldSelectedIndex, SelectedIndex);
  647. _oldSelectedIndex = SelectedIndex;
  648. }
  649. else if (e.PropertyName == nameof(ISelectionModel.SelectedItem) && _oldSelectedItem != SelectedItem)
  650. {
  651. RaisePropertyChanged(SelectedItemProperty, _oldSelectedItem, SelectedItem);
  652. _oldSelectedItem = SelectedItem;
  653. }
  654. else if (e.PropertyName == nameof(InternalSelectionModel.WritableSelectedItems) &&
  655. _oldSelectedItems != (Selection as InternalSelectionModel)?.SelectedItems)
  656. {
  657. RaisePropertyChanged(
  658. SelectedItemsProperty,
  659. new Optional<IList?>(_oldSelectedItems),
  660. new BindingValue<IList?>(SelectedItems));
  661. _oldSelectedItems = SelectedItems;
  662. }
  663. }
  664. /// <summary>
  665. /// Called when <see cref="ISelectionModel.SelectionChanged"/> event is raised on
  666. /// <see cref="Selection"/>.
  667. /// </summary>
  668. /// <param name="sender">The sender.</param>
  669. /// <param name="e">The event args.</param>
  670. private void OnSelectionModelSelectionChanged(object sender, SelectionModelSelectionChangedEventArgs e)
  671. {
  672. void Mark(int index, bool selected)
  673. {
  674. var container = ItemContainerGenerator.ContainerFromIndex(index);
  675. if (container != null)
  676. {
  677. MarkContainerSelected(container, selected);
  678. }
  679. }
  680. foreach (var i in e.SelectedIndexes)
  681. {
  682. Mark(i, true);
  683. }
  684. foreach (var i in e.DeselectedIndexes)
  685. {
  686. Mark(i, false);
  687. }
  688. var route = BuildEventRoute(SelectionChangedEvent);
  689. if (route.HasHandlers)
  690. {
  691. var ev = new SelectionChangedEventArgs(
  692. SelectionChangedEvent,
  693. e.DeselectedItems.ToList(),
  694. e.SelectedItems.ToList());
  695. RaiseEvent(ev);
  696. }
  697. }
  698. /// <summary>
  699. /// Called when <see cref="ISelectionModel.LostSelection"/> event is raised on
  700. /// <see cref="Selection"/>.
  701. /// </summary>
  702. /// <param name="sender">The sender.</param>
  703. /// <param name="e">The event args.</param>
  704. private void OnSelectionModelLostSelection(object sender, EventArgs e)
  705. {
  706. if (AlwaysSelected && Items is object)
  707. {
  708. SelectedIndex = 0;
  709. }
  710. }
  711. private void AutoScrollToSelectedItemIfNecessary()
  712. {
  713. if (AutoScrollToSelectedItem &&
  714. !_hasScrolledToSelectedItem &&
  715. Presenter is object &&
  716. Selection.AnchorIndex >= 0 &&
  717. ((IVisual)this).IsAttachedToVisualTree)
  718. {
  719. ScrollIntoView(Selection.AnchorIndex);
  720. _hasScrolledToSelectedItem = true;
  721. }
  722. }
  723. /// <summary>
  724. /// Called when a container raises the <see cref="IsSelectedChangedEvent"/>.
  725. /// </summary>
  726. /// <param name="e">The event.</param>
  727. private void ContainerSelectionChanged(RoutedEventArgs e)
  728. {
  729. if (!_ignoreContainerSelectionChanged &&
  730. e.Source is IControl control &&
  731. e.Source is ISelectable selectable &&
  732. control.LogicalParent == this &&
  733. ItemContainerGenerator?.IndexFromContainer(control) != -1)
  734. {
  735. UpdateSelection(control, selectable.IsSelected);
  736. }
  737. if (e.Source != this)
  738. {
  739. e.Handled = true;
  740. }
  741. }
  742. /// <summary>
  743. /// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>.
  744. /// </summary>
  745. /// <param name="container">The container.</param>
  746. /// <param name="selected">Whether the control is selected</param>
  747. /// <returns>The previous selection state.</returns>
  748. private bool MarkContainerSelected(IControl container, bool selected)
  749. {
  750. try
  751. {
  752. bool result;
  753. _ignoreContainerSelectionChanged = true;
  754. if (container is ISelectable selectable)
  755. {
  756. result = selectable.IsSelected;
  757. selectable.IsSelected = selected;
  758. }
  759. else
  760. {
  761. result = container.Classes.Contains(":selected");
  762. ((IPseudoClasses)container.Classes).Set(":selected", selected);
  763. }
  764. return result;
  765. }
  766. finally
  767. {
  768. _ignoreContainerSelectionChanged = false;
  769. }
  770. }
  771. private void UpdateContainerSelection()
  772. {
  773. if (Presenter?.Panel is IPanel panel)
  774. {
  775. foreach (var container in panel.Children)
  776. {
  777. MarkContainerSelected(
  778. container,
  779. Selection.IsSelected(ItemContainerGenerator.IndexFromContainer(container)));
  780. }
  781. }
  782. }
  783. private ISelectionModel CreateDefaultSelectionModel()
  784. {
  785. return new InternalSelectionModel
  786. {
  787. SingleSelect = !SelectionMode.HasFlagCustom(SelectionMode.Multiple),
  788. };
  789. }
  790. private void InitializeSelectionModel(ISelectionModel model)
  791. {
  792. if (_updateState is null)
  793. {
  794. model.Source = Items;
  795. }
  796. model.PropertyChanged += OnSelectionModelPropertyChanged;
  797. model.SelectionChanged += OnSelectionModelSelectionChanged;
  798. model.LostSelection += OnSelectionModelLostSelection;
  799. if (model.SingleSelect)
  800. {
  801. SelectionMode &= ~SelectionMode.Multiple;
  802. }
  803. else
  804. {
  805. SelectionMode |= SelectionMode.Multiple;
  806. }
  807. _oldSelectedIndex = model.SelectedIndex;
  808. _oldSelectedItem = model.SelectedItem;
  809. if (AlwaysSelected && model.Count == 0)
  810. {
  811. model.SelectedIndex = 0;
  812. }
  813. UpdateContainerSelection();
  814. if (SelectedIndex != -1)
  815. {
  816. RaiseEvent(new SelectionChangedEventArgs(
  817. SelectionChangedEvent,
  818. Array.Empty<object>(),
  819. Selection.SelectedItems.ToList()));
  820. }
  821. }
  822. private void DeinitializeSelectionModel(ISelectionModel? model)
  823. {
  824. if (model is object)
  825. {
  826. model.PropertyChanged -= OnSelectionModelPropertyChanged;
  827. model.SelectionChanged -= OnSelectionModelSelectionChanged;
  828. }
  829. }
  830. private void BeginUpdating()
  831. {
  832. _updateState ??= new UpdateState();
  833. _updateState.UpdateCount++;
  834. }
  835. private void EndUpdating()
  836. {
  837. if (_updateState is object && --_updateState.UpdateCount == 0)
  838. {
  839. var state = _updateState;
  840. _updateState = null;
  841. if (state.Selection.HasValue)
  842. {
  843. Selection = state.Selection.Value;
  844. }
  845. if (state.SelectedItems.HasValue)
  846. {
  847. SelectedItems = state.SelectedItems.Value;
  848. }
  849. Selection.Source = Items;
  850. if (Items is null)
  851. {
  852. Selection.Clear();
  853. }
  854. if (state.SelectedIndex.HasValue)
  855. {
  856. SelectedIndex = state.SelectedIndex.Value;
  857. }
  858. else if (state.SelectedItem.HasValue)
  859. {
  860. SelectedItem = state.SelectedItem.Value;
  861. }
  862. }
  863. }
  864. // When in a BeginInit..EndInit block, or when the DataContext is updating, we need to
  865. // defer changes to the selection model because we have no idea in which order properties
  866. // will be set. Consider:
  867. //
  868. // - Both Items and SelectedItem are bound
  869. // - The DataContext changes
  870. // - The binding for SelectedItem updates first, producing an item
  871. // - Items is searched to find the index of the new selected item
  872. // - However Items isn't yet updated; the item is not found
  873. // - SelectedIndex is incorrectly set to -1
  874. //
  875. // This logic cannot be encapsulated in SelectionModel because the selection model can also
  876. // be bound, consider:
  877. //
  878. // - Both Items and Selection are bound
  879. // - The DataContext changes
  880. // - The binding for Items updates first
  881. // - The new items are assigned to Selection.Source
  882. // - The binding for Selection updates, producing a new SelectionModel
  883. // - Both the old and new SelectionModels have the incorrect Source
  884. private class UpdateState
  885. {
  886. private Optional<int> _selectedIndex;
  887. private Optional<object?> _selectedItem;
  888. public int UpdateCount { get; set; }
  889. public Optional<ISelectionModel> Selection { get; set; }
  890. public Optional<IList?> SelectedItems { get; set; }
  891. public Optional<int> SelectedIndex
  892. {
  893. get => _selectedIndex;
  894. set
  895. {
  896. _selectedIndex = value;
  897. _selectedItem = default;
  898. }
  899. }
  900. public Optional<object?> SelectedItem
  901. {
  902. get => _selectedItem;
  903. set
  904. {
  905. _selectedItem = value;
  906. _selectedIndex = default;
  907. }
  908. }
  909. }
  910. }
  911. }