SelectingItemsControl.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. // Copyright (c) The Perspex Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Collections;
  5. using System.Collections.Specialized;
  6. using System.Linq;
  7. using Perspex.Collections;
  8. using Perspex.Controls.Generators;
  9. using Perspex.Input;
  10. using Perspex.Interactivity;
  11. using Perspex.Styling;
  12. using Perspex.VisualTree;
  13. namespace Perspex.Controls.Primitives
  14. {
  15. /// <summary>
  16. /// An <see cref="ItemsControl"/> that maintains a selection.
  17. /// </summary>
  18. /// <remarks>
  19. /// <para>
  20. /// <see cref="SelectingItemsControl"/> provides a base class for <see cref="ItemsControl"/>s
  21. /// that maintain a selection (single or multiple). By default only its
  22. /// <see cref="SelectedIndex"/> and <see cref="SelectedItem"/> properties are visible; the
  23. /// multiple selection properties <see cref="SelectedIndexes"/> and <see cref="SelectedItems"/>
  24. /// together with the <see cref="SelectionMode"/> properties are protected, however a derived
  25. /// class can expose these if it wishes to support multiple selection.
  26. /// </para>
  27. /// <para>
  28. /// <see cref="SelectingItemsControl"/> maintains a selection respecting the current
  29. /// <see cref="SelectionMode"/> but it does not react to user input; this must be handled in a
  30. /// derived class. It does, however, respond to <see cref="IsSelectedChangedEvent"/> events
  31. /// from items and updates the selection accordingly.
  32. /// </para>
  33. /// </remarks>
  34. public class SelectingItemsControl : ItemsControl
  35. {
  36. /// <summary>
  37. /// Defines the <see cref="SelectedIndex"/> property.
  38. /// </summary>
  39. public static readonly PerspexProperty<int> SelectedIndexProperty =
  40. PerspexProperty.RegisterDirect<SelectingItemsControl, int>(
  41. nameof(SelectedIndex),
  42. o => o.SelectedIndex,
  43. (o, v) => o.SelectedIndex = v);
  44. /// <summary>
  45. /// Defines the <see cref="SelectedItem"/> property.
  46. /// </summary>
  47. public static readonly PerspexProperty<object> SelectedItemProperty =
  48. PerspexProperty.RegisterDirect<SelectingItemsControl, object>(
  49. nameof(SelectedItem),
  50. o => o.SelectedItem,
  51. (o, v) => o.SelectedItem = v);
  52. /// <summary>
  53. /// Defines the <see cref="SelectedIndexes"/> property.
  54. /// </summary>
  55. protected static readonly PerspexProperty<IPerspexList<int>> SelectedIndexesProperty =
  56. PerspexProperty.RegisterDirect<SelectingItemsControl, IPerspexList<int>>(
  57. nameof(SelectedIndexes),
  58. o => o.SelectedIndexes);
  59. /// <summary>
  60. /// Defines the <see cref="SelectedItems"/> property.
  61. /// </summary>
  62. protected static readonly PerspexProperty<IPerspexList<object>> SelectedItemsProperty =
  63. PerspexProperty.RegisterDirect<SelectingItemsControl, IPerspexList<object>>(
  64. nameof(SelectedItems),
  65. o => o.SelectedItems);
  66. /// <summary>
  67. /// Defines the <see cref="SelectionMode"/> property.
  68. /// </summary>
  69. protected static readonly PerspexProperty<SelectionMode> SelectionModeProperty =
  70. PerspexProperty.Register<SelectingItemsControl, SelectionMode>(
  71. nameof(SelectionMode));
  72. /// <summary>
  73. /// Event that should be raised by items that implement <see cref="ISelectable"/> to
  74. /// notify the parent <see cref="SelectingItemsControl"/> that their selection state
  75. /// has changed.
  76. /// </summary>
  77. public static readonly RoutedEvent<RoutedEventArgs> IsSelectedChangedEvent =
  78. RoutedEvent.Register<SelectingItemsControl, RoutedEventArgs>("IsSelectedChanged", RoutingStrategies.Bubble);
  79. private PerspexList<int> _selectedIndexes = new PerspexList<int>();
  80. private PerspexList<object> _selectedItems = new PerspexList<object>();
  81. private bool _ignoreContainerSelectionChanged;
  82. /// <summary>
  83. /// Initializes static members of the <see cref="SelectingItemsControl"/> class.
  84. /// </summary>
  85. static SelectingItemsControl()
  86. {
  87. IsSelectedChangedEvent.AddClassHandler<SelectingItemsControl>(x => x.ContainerSelectionChanged);
  88. }
  89. /// <summary>
  90. /// Initializes a new instance of the <see cref="SelectingItemsControl"/> class.
  91. /// </summary>
  92. public SelectingItemsControl()
  93. {
  94. ItemContainerGenerator.ContainersInitialized.Subscribe(ContainersInitialized);
  95. _selectedIndexes.Validate = ValidateIndex;
  96. _selectedIndexes.ForEachItem(SelectedIndexAdded, SelectedIndexRemoved, SelectionReset);
  97. _selectedItems.ForEachItem(SelectedItemAdded, SelectedItemRemoved, SelectionReset);
  98. }
  99. /// <summary>
  100. /// Gets or sets the index of the selected item.
  101. /// </summary>
  102. public int SelectedIndex
  103. {
  104. get
  105. {
  106. return _selectedIndexes.Count > 0 ? _selectedIndexes[0]: -1;
  107. }
  108. set
  109. {
  110. var old = SelectedIndex;
  111. var effective = (value >= 0 && value < Items?.Cast<object>().Count()) ? value : -1;
  112. if (old != effective)
  113. {
  114. _selectedIndexes.Clear();
  115. if (effective != -1)
  116. {
  117. _selectedIndexes.Add(effective);
  118. }
  119. RaisePropertyChanged(SelectedIndexProperty, old, effective, BindingPriority.LocalValue);
  120. }
  121. }
  122. }
  123. /// <summary>
  124. /// Gets or sets the selected item.
  125. /// </summary>
  126. public object SelectedItem
  127. {
  128. get
  129. {
  130. return _selectedItems.FirstOrDefault();
  131. }
  132. set
  133. {
  134. var old = SelectedItem;
  135. var effective = Items?.Cast<object>().Contains(value) == true ? value : null;
  136. if (effective != old)
  137. {
  138. _selectedItems.Clear();
  139. if (effective != null)
  140. {
  141. _selectedItems.Add(effective);
  142. }
  143. RaisePropertyChanged(SelectedItemProperty, old, effective, BindingPriority.LocalValue);
  144. }
  145. }
  146. }
  147. /// <summary>
  148. /// Gets the selected indexes.
  149. /// </summary>
  150. protected IPerspexList<int> SelectedIndexes
  151. {
  152. get { return _selectedIndexes; }
  153. }
  154. /// <summary>
  155. /// Gets the selected items.
  156. /// </summary>
  157. protected IPerspexList<object> SelectedItems
  158. {
  159. get { return _selectedItems; }
  160. }
  161. /// <summary>
  162. /// Gets or sets the selection mode.
  163. /// </summary>
  164. protected SelectionMode SelectionMode
  165. {
  166. get { return GetValue(SelectionModeProperty); }
  167. set { SetValue(SelectionModeProperty, value); }
  168. }
  169. /// <summary>
  170. /// Gets a value indicating whether <see cref="SelectionMode.AlwaysSelected"/> is set.
  171. /// </summary>
  172. protected bool AlwaysSelected => (SelectionMode & SelectionMode.AlwaysSelected) != 0;
  173. /// <summary>
  174. /// Tries to get the container that was the source of an event.
  175. /// </summary>
  176. /// <param name="eventSource">The control that raised the event.</param>
  177. /// <returns>The container or null if the event did not originate in a container.</returns>
  178. protected IControl GetContainerFromEventSource(IInteractive eventSource)
  179. {
  180. var item = ((IVisual)eventSource).GetSelfAndVisualAncestors()
  181. .OfType<ILogical>()
  182. .FirstOrDefault(x => x.LogicalParent == this);
  183. return item as IControl;
  184. }
  185. /// <inheritdoc/>
  186. protected override void ItemsChanged(PerspexPropertyChangedEventArgs e)
  187. {
  188. base.ItemsChanged(e);
  189. if (SelectedIndex != -1)
  190. {
  191. SelectedIndex = IndexOf((IEnumerable)e.NewValue, SelectedItem);
  192. }
  193. else if (AlwaysSelected && Items != null & Items.Cast<object>().Any())
  194. {
  195. SelectedIndex = 0;
  196. }
  197. }
  198. /// <inheritdoc/>
  199. protected override void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  200. {
  201. base.ItemsCollectionChanged(sender, e);
  202. switch (e.Action)
  203. {
  204. case NotifyCollectionChangedAction.Add:
  205. if (AlwaysSelected && SelectedIndex == -1)
  206. {
  207. SelectedIndex = 0;
  208. }
  209. break;
  210. case NotifyCollectionChangedAction.Remove:
  211. case NotifyCollectionChangedAction.Replace:
  212. var selectedIndex = SelectedIndex;
  213. if (selectedIndex >= e.OldStartingIndex &&
  214. selectedIndex < e.OldStartingIndex + e.OldItems.Count)
  215. {
  216. if (!AlwaysSelected)
  217. {
  218. SelectedIndex = -1;
  219. }
  220. else
  221. {
  222. LostSelection();
  223. }
  224. }
  225. break;
  226. case NotifyCollectionChangedAction.Reset:
  227. SelectedIndex = IndexOf(e.NewItems, SelectedItem);
  228. break;
  229. }
  230. }
  231. /// <summary>
  232. /// Updates the selection for an item.
  233. /// </summary>
  234. /// <param name="index">The index of the item.</param>
  235. /// <param name="select">Whether the item should be selected or unselected.</param>
  236. protected void UpdateSelection(int index, bool select)
  237. {
  238. if (index != -1)
  239. {
  240. if (select)
  241. {
  242. var toggle = (SelectionMode & SelectionMode.Toggle) != 0;
  243. if (!toggle)
  244. {
  245. SelectedIndex = index;
  246. }
  247. else
  248. {
  249. var i = SelectedIndexes.IndexOf(index);
  250. if (i != -1 && (!AlwaysSelected || SelectedItems.Count > 1))
  251. {
  252. SelectedIndexes.RemoveAt(i);
  253. }
  254. else
  255. {
  256. SelectedIndexes.Add(index);
  257. }
  258. }
  259. }
  260. else
  261. {
  262. LostSelection();
  263. }
  264. }
  265. }
  266. /// <summary>
  267. /// Updates the selection for a container.
  268. /// </summary>
  269. /// <param name="container">The container.</param>
  270. /// <param name="select">Whether the container should be selected or unselected.</param>
  271. protected void UpdateSelection(IControl container, bool select)
  272. {
  273. var index = ItemContainerGenerator.IndexFromContainer(container);
  274. if (index != -1)
  275. {
  276. UpdateSelection(index, select);
  277. }
  278. }
  279. /// <summary>
  280. /// Updates the selection based on an event source that may have originated in a container
  281. /// that belongs to the control.
  282. /// </summary>
  283. /// <param name="eventSource">The control that raised the event.</param>
  284. /// <param name="select">Whether the container should be selected or unselected.</param>
  285. /// <returns>
  286. /// True if the event originated from a container that belongs to the control; otherwise
  287. /// false.
  288. /// </returns>
  289. protected bool UpdateSelectionFromEventSource(IInteractive eventSource, bool select)
  290. {
  291. var item = GetContainerFromEventSource(eventSource);
  292. if (item != null)
  293. {
  294. UpdateSelection(item, select);
  295. return true;
  296. }
  297. return false;
  298. }
  299. /// <summary>
  300. /// Gets the index of an item in a collection.
  301. /// </summary>
  302. /// <param name="items">The collection.</param>
  303. /// <param name="item">The item.</param>
  304. /// <returns>The index of the item or -1 if the item was not found.</returns>
  305. private static int IndexOf(IEnumerable items, object item)
  306. {
  307. if (items != null && item != null)
  308. {
  309. var list = items as IList;
  310. if (list != null)
  311. {
  312. return list.IndexOf(item);
  313. }
  314. else
  315. {
  316. int index = 0;
  317. foreach (var i in items)
  318. {
  319. if (Equals(i, item))
  320. {
  321. return index;
  322. }
  323. ++index;
  324. }
  325. }
  326. }
  327. return -1;
  328. }
  329. /// <summary>
  330. /// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>.
  331. /// </summary>
  332. /// <param name="container">The container.</param>
  333. /// <param name="selected">Whether the control is selected</param>
  334. private void MarkContainerSelected(IControl container, bool selected)
  335. {
  336. try
  337. {
  338. var selectable = container as ISelectable;
  339. var styleable = container as IStyleable;
  340. _ignoreContainerSelectionChanged = true;
  341. if (selectable != null)
  342. {
  343. selectable.IsSelected = selected;
  344. }
  345. else if (styleable != null)
  346. {
  347. if (selected)
  348. {
  349. styleable.Classes.Add(":selected");
  350. }
  351. else
  352. {
  353. styleable.Classes.Remove(":selected");
  354. }
  355. }
  356. }
  357. finally
  358. {
  359. _ignoreContainerSelectionChanged = false;
  360. }
  361. }
  362. /// <summary>
  363. /// Called when new containers are initialized by the <see cref="ItemContainerGenerator"/>.
  364. /// </summary>
  365. /// <param name="containers">The containers.</param>
  366. private void ContainersInitialized(ItemContainers containers)
  367. {
  368. var selectedIndex = SelectedIndex;
  369. var selectedContainer = containers.Items.OfType<ISelectable>().FirstOrDefault(x => x.IsSelected);
  370. if (selectedContainer != null)
  371. {
  372. SelectedIndex = containers.Items.IndexOf((IControl)selectedContainer) + containers.StartingIndex;
  373. }
  374. else if (selectedIndex >= containers.StartingIndex &&
  375. selectedIndex < containers.StartingIndex + containers.Items.Count)
  376. {
  377. var container = containers.Items[selectedIndex - containers.StartingIndex];
  378. MarkContainerSelected(container, true);
  379. }
  380. }
  381. /// <summary>
  382. /// Called when a container raises the <see cref="IsSelectedChangedEvent"/>.
  383. /// </summary>
  384. /// <param name="e">The event.</param>
  385. private void ContainerSelectionChanged(RoutedEventArgs e)
  386. {
  387. if (!_ignoreContainerSelectionChanged)
  388. {
  389. var selectable = (ISelectable)e.Source;
  390. if (selectable != null)
  391. {
  392. UpdateSelectionFromEventSource(e.Source, selectable.IsSelected);
  393. }
  394. }
  395. }
  396. /// <summary>
  397. /// Sets an item container's 'selected' class or <see cref="ISelectable.IsSelected"/>.
  398. /// </summary>
  399. /// <param name="index">The index of the item.</param>
  400. /// <param name="selected">Whether the control is selected</param>
  401. /// <returns>The container.</returns>
  402. private IControl MarkIndexSelected(int index, bool selected)
  403. {
  404. var container = ItemContainerGenerator.ContainerFromIndex(index);
  405. if (container != null)
  406. {
  407. MarkContainerSelected(container, selected);
  408. }
  409. return container;
  410. }
  411. /// <summary>
  412. /// Called when an index is added to the <see cref="SelectedIndexes"/> collection.
  413. /// </summary>
  414. /// <param name="listIndex">The index in the SelectedIndexes collection.</param>
  415. /// <param name="itemIndex">The item index.</param>
  416. private void SelectedIndexAdded(int listIndex, int itemIndex)
  417. {
  418. if (SelectedIndexes.Count == 1)
  419. {
  420. RaisePropertyChanged(SelectedIndexProperty, -1, itemIndex, BindingPriority.LocalValue);
  421. }
  422. if (SelectedItems.Count != SelectedIndexes.Count)
  423. {
  424. var item = Items.Cast<object>().ElementAt(itemIndex);
  425. SelectedItems.Insert(listIndex, item);
  426. }
  427. var container = MarkIndexSelected(itemIndex, true);
  428. if (container != null && Presenter?.Panel != null)
  429. {
  430. KeyboardNavigation.SetTabOnceActiveElement((InputElement)Presenter.Panel, container);
  431. }
  432. }
  433. /// <summary>
  434. /// Called when an index is removed from the <see cref="SelectedIndexes"/> collection.
  435. /// </summary>
  436. /// <param name="listIndex">The index in the SelectedIndexes collection.</param>
  437. /// <param name="itemIndex">The item index.</param>
  438. private void SelectedIndexRemoved(int listIndex, int itemIndex)
  439. {
  440. if (SelectedIndexes.Count == 0)
  441. {
  442. RaisePropertyChanged(SelectedIndexProperty, itemIndex, -1, BindingPriority.LocalValue);
  443. }
  444. if (SelectedIndexes.Count != SelectedItems.Count)
  445. {
  446. SelectedItems.RemoveAt(listIndex);
  447. }
  448. MarkIndexSelected(itemIndex, false);
  449. }
  450. /// <summary>
  451. /// Called when an item is added to the <see cref="SelectedItems"/> collection.
  452. /// </summary>
  453. /// <param name="index">The index in the SelectedItems collection.</param>
  454. /// <param name="item">The item.</param>
  455. private void SelectedItemAdded(int index, object item)
  456. {
  457. if (SelectedItems.Count == 1)
  458. {
  459. RaisePropertyChanged(SelectedItemProperty, null, item, BindingPriority.LocalValue);
  460. }
  461. if (SelectedIndexes.Count != SelectedItems.Count)
  462. {
  463. SelectedIndexes.Insert(index, IndexOf(Items, item));
  464. }
  465. }
  466. /// <summary>
  467. /// Called when an item is removed from the <see cref="SelectedItems"/> collection.
  468. /// </summary>
  469. /// <param name="index">The index in the SelectedItems collection.</param>
  470. /// <param name="item">The item.</param>
  471. private void SelectedItemRemoved(int index, object item)
  472. {
  473. if (SelectedIndexes.Count != SelectedItems.Count)
  474. {
  475. SelectedIndexes.RemoveAt(index);
  476. }
  477. }
  478. /// <summary>
  479. /// Called when the <see cref="SelectedItems"/> collection is reset.
  480. /// </summary>
  481. private void SelectionReset()
  482. {
  483. if (SelectedIndexes.Count > 0)
  484. {
  485. SelectedIndexes.Clear();
  486. }
  487. if (SelectedItems.Count > 0)
  488. {
  489. SelectedItems.Clear();
  490. }
  491. foreach (var container in ItemContainerGenerator.Containers)
  492. {
  493. MarkContainerSelected(container, false);
  494. }
  495. }
  496. /// <summary>
  497. /// Validates items added to the <see cref="SelectedIndexes"/> collection.
  498. /// </summary>
  499. /// <param name="index">The index to be added.</param>
  500. private void ValidateIndex(int index)
  501. {
  502. if (index < 0 || index >= Items?.Cast<object>().Count())
  503. {
  504. throw new IndexOutOfRangeException();
  505. }
  506. }
  507. /// <summary>
  508. /// Called when the currently selected item is lost and the selection must be changed
  509. /// depending on the <see cref="SelectionMode"/> property.
  510. /// </summary>
  511. private void LostSelection()
  512. {
  513. var items = Items?.Cast<object>();
  514. if (items != null && AlwaysSelected)
  515. {
  516. var index = Math.Min(SelectedIndex, items.Count() - 1);
  517. if (index > -1)
  518. {
  519. SelectedItem = items.ElementAt(index);
  520. return;
  521. }
  522. }
  523. SelectedIndex = -1;
  524. }
  525. }
  526. }