ItemsControl.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // Copyright (c) The Avalonia 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.Generic;
  6. using System.Collections.Specialized;
  7. using Avalonia.Collections;
  8. using Avalonia.Controls.Generators;
  9. using Avalonia.Controls.Presenters;
  10. using Avalonia.Controls.Primitives;
  11. using Avalonia.Controls.Templates;
  12. using Avalonia.Controls.Utils;
  13. using Avalonia.Input;
  14. using Avalonia.LogicalTree;
  15. using Avalonia.Metadata;
  16. using Avalonia.VisualTree;
  17. namespace Avalonia.Controls
  18. {
  19. /// <summary>
  20. /// Displays a collection of items.
  21. /// </summary>
  22. public class ItemsControl : TemplatedControl, IItemsPresenterHost
  23. {
  24. /// <summary>
  25. /// The default value for the <see cref="ItemsPanel"/> property.
  26. /// </summary>
  27. private static readonly FuncTemplate<IPanel> DefaultPanel =
  28. new FuncTemplate<IPanel>(() => new StackPanel());
  29. /// <summary>
  30. /// Defines the <see cref="Items"/> property.
  31. /// </summary>
  32. public static readonly DirectProperty<ItemsControl, IEnumerable> ItemsProperty =
  33. AvaloniaProperty.RegisterDirect<ItemsControl, IEnumerable>(nameof(Items), o => o.Items, (o, v) => o.Items = v);
  34. /// <summary>
  35. /// Defines the <see cref="ItemCount"/> property.
  36. /// </summary>
  37. public static readonly DirectProperty<ItemsControl, int> ItemCountProperty =
  38. AvaloniaProperty.RegisterDirect<ItemsControl, int>(nameof(ItemCount), o => o.ItemCount);
  39. /// <summary>
  40. /// Defines the <see cref="ItemsPanel"/> property.
  41. /// </summary>
  42. public static readonly StyledProperty<ITemplate<IPanel>> ItemsPanelProperty =
  43. AvaloniaProperty.Register<ItemsControl, ITemplate<IPanel>>(nameof(ItemsPanel), DefaultPanel);
  44. /// <summary>
  45. /// Defines the <see cref="ItemTemplate"/> property.
  46. /// </summary>
  47. public static readonly StyledProperty<IDataTemplate> ItemTemplateProperty =
  48. AvaloniaProperty.Register<ItemsControl, IDataTemplate>(nameof(ItemTemplate));
  49. private IEnumerable _items = new AvaloniaList<object>();
  50. private int _itemCount;
  51. private IItemContainerGenerator _itemContainerGenerator;
  52. private IDisposable _itemsCollectionChangedSubscription;
  53. /// <summary>
  54. /// Initializes static members of the <see cref="ItemsControl"/> class.
  55. /// </summary>
  56. static ItemsControl()
  57. {
  58. ItemsProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemsChanged(e));
  59. ItemTemplateProperty.Changed.AddClassHandler<ItemsControl>((x, e) => x.ItemTemplateChanged(e));
  60. }
  61. /// <summary>
  62. /// Initializes a new instance of the <see cref="ItemsControl"/> class.
  63. /// </summary>
  64. public ItemsControl()
  65. {
  66. PseudoClasses.Add(":empty");
  67. SubscribeToItems(_items);
  68. }
  69. /// <summary>
  70. /// Gets the <see cref="IItemContainerGenerator"/> for the control.
  71. /// </summary>
  72. public IItemContainerGenerator ItemContainerGenerator
  73. {
  74. get
  75. {
  76. if (_itemContainerGenerator == null)
  77. {
  78. _itemContainerGenerator = CreateItemContainerGenerator();
  79. if (_itemContainerGenerator != null)
  80. {
  81. _itemContainerGenerator.ItemTemplate = ItemTemplate;
  82. _itemContainerGenerator.Materialized += (_, e) => OnContainersMaterialized(e);
  83. _itemContainerGenerator.Dematerialized += (_, e) => OnContainersDematerialized(e);
  84. _itemContainerGenerator.Recycled += (_, e) => OnContainersRecycled(e);
  85. }
  86. }
  87. return _itemContainerGenerator;
  88. }
  89. }
  90. /// <summary>
  91. /// Gets or sets the items to display.
  92. /// </summary>
  93. [Content]
  94. public IEnumerable Items
  95. {
  96. get { return _items; }
  97. set { SetAndRaise(ItemsProperty, ref _items, value); }
  98. }
  99. /// <summary>
  100. /// Gets the number of items in <see cref="Items"/>.
  101. /// </summary>
  102. public int ItemCount
  103. {
  104. get => _itemCount;
  105. private set => SetAndRaise(ItemCountProperty, ref _itemCount, value);
  106. }
  107. /// <summary>
  108. /// Gets or sets the panel used to display the items.
  109. /// </summary>
  110. public ITemplate<IPanel> ItemsPanel
  111. {
  112. get { return GetValue(ItemsPanelProperty); }
  113. set { SetValue(ItemsPanelProperty, value); }
  114. }
  115. /// <summary>
  116. /// Gets or sets the data template used to display the items in the control.
  117. /// </summary>
  118. public IDataTemplate ItemTemplate
  119. {
  120. get { return GetValue(ItemTemplateProperty); }
  121. set { SetValue(ItemTemplateProperty, value); }
  122. }
  123. /// <summary>
  124. /// Gets the items presenter control.
  125. /// </summary>
  126. public IItemsPresenter Presenter
  127. {
  128. get;
  129. protected set;
  130. }
  131. /// <inheritdoc/>
  132. void IItemsPresenterHost.RegisterItemsPresenter(IItemsPresenter presenter)
  133. {
  134. Presenter = presenter;
  135. ItemContainerGenerator.Clear();
  136. }
  137. /// <summary>
  138. /// Gets the item at the specified index in a collection.
  139. /// </summary>
  140. /// <param name="items">The collection.</param>
  141. /// <param name="index">The index.</param>
  142. /// <returns>The index of the item or -1 if the item was not found.</returns>
  143. protected static object ElementAt(IEnumerable items, int index)
  144. {
  145. if (index != -1 && index < items.Count())
  146. {
  147. return items.ElementAt(index) ?? null;
  148. }
  149. else
  150. {
  151. return null;
  152. }
  153. }
  154. /// <summary>
  155. /// Gets the index of an item in a collection.
  156. /// </summary>
  157. /// <param name="items">The collection.</param>
  158. /// <param name="item">The item.</param>
  159. /// <returns>The index of the item or -1 if the item was not found.</returns>
  160. protected static int IndexOf(IEnumerable items, object item)
  161. {
  162. if (items != null && item != null)
  163. {
  164. var list = items as IList;
  165. if (list != null)
  166. {
  167. return list.IndexOf(item);
  168. }
  169. else
  170. {
  171. int index = 0;
  172. foreach (var i in items)
  173. {
  174. if (Equals(i, item))
  175. {
  176. return index;
  177. }
  178. ++index;
  179. }
  180. }
  181. }
  182. return -1;
  183. }
  184. /// <summary>
  185. /// Creates the <see cref="ItemContainerGenerator"/> for the control.
  186. /// </summary>
  187. /// <returns>
  188. /// An <see cref="IItemContainerGenerator"/> or null.
  189. /// </returns>
  190. /// <remarks>
  191. /// Certain controls such as <see cref="TabControl"/> don't actually create item
  192. /// containers; however they want it to be ItemsControls so that they have an Items
  193. /// property etc. In this case, a derived class can override this method to return null
  194. /// in order to disable the creation of item containers.
  195. /// </remarks>
  196. protected virtual IItemContainerGenerator CreateItemContainerGenerator()
  197. {
  198. return new ItemContainerGenerator(this);
  199. }
  200. /// <summary>
  201. /// Called when new containers are materialized for the <see cref="ItemsControl"/> by its
  202. /// <see cref="ItemContainerGenerator"/>.
  203. /// </summary>
  204. /// <param name="e">The details of the containers.</param>
  205. protected virtual void OnContainersMaterialized(ItemContainerEventArgs e)
  206. {
  207. foreach (var container in e.Containers)
  208. {
  209. // If the item is its own container, then it will be added to the logical tree when
  210. // it was added to the Items collection.
  211. if (container.ContainerControl != null && container.ContainerControl != container.Item)
  212. {
  213. LogicalChildren.Add(container.ContainerControl);
  214. }
  215. }
  216. }
  217. /// <summary>
  218. /// Called when containers are dematerialized for the <see cref="ItemsControl"/> by its
  219. /// <see cref="ItemContainerGenerator"/>.
  220. /// </summary>
  221. /// <param name="e">The details of the containers.</param>
  222. protected virtual void OnContainersDematerialized(ItemContainerEventArgs e)
  223. {
  224. foreach (var container in e.Containers)
  225. {
  226. // If the item is its own container, then it will be removed from the logical tree
  227. // when it is removed from the Items collection.
  228. if (container?.ContainerControl != container?.Item)
  229. {
  230. LogicalChildren.Remove(container.ContainerControl);
  231. }
  232. }
  233. }
  234. /// <summary>
  235. /// Called when containers are recycled for the <see cref="ItemsControl"/> by its
  236. /// <see cref="ItemContainerGenerator"/>.
  237. /// </summary>
  238. /// <param name="e">The details of the containers.</param>
  239. protected virtual void OnContainersRecycled(ItemContainerEventArgs e)
  240. {
  241. }
  242. /// <summary>
  243. /// Handles directional navigation within the <see cref="ItemsControl"/>.
  244. /// </summary>
  245. /// <param name="e">The key events.</param>
  246. protected override void OnKeyDown(KeyEventArgs e)
  247. {
  248. if (!e.Handled)
  249. {
  250. var focus = FocusManager.Instance;
  251. var direction = e.Key.ToNavigationDirection();
  252. var container = Presenter?.Panel as INavigableContainer;
  253. if (container == null ||
  254. focus.Current == null ||
  255. direction == null ||
  256. direction.Value.IsTab())
  257. {
  258. return;
  259. }
  260. IVisual current = focus.Current;
  261. while (current != null)
  262. {
  263. if (current.VisualParent == container && current is IInputElement inputElement)
  264. {
  265. IInputElement next = GetNextControl(container, direction.Value, inputElement, false);
  266. if (next != null)
  267. {
  268. focus.Focus(next, NavigationMethod.Directional);
  269. e.Handled = true;
  270. }
  271. break;
  272. }
  273. current = current.VisualParent;
  274. }
  275. }
  276. base.OnKeyDown(e);
  277. }
  278. /// <summary>
  279. /// Called when the <see cref="Items"/> property changes.
  280. /// </summary>
  281. /// <param name="e">The event args.</param>
  282. protected virtual void ItemsChanged(AvaloniaPropertyChangedEventArgs e)
  283. {
  284. _itemsCollectionChangedSubscription?.Dispose();
  285. _itemsCollectionChangedSubscription = null;
  286. var oldValue = e.OldValue as IEnumerable;
  287. var newValue = e.NewValue as IEnumerable;
  288. UpdateItemCount();
  289. RemoveControlItemsFromLogicalChildren(oldValue);
  290. AddControlItemsToLogicalChildren(newValue);
  291. if (Presenter != null)
  292. {
  293. Presenter.Items = newValue;
  294. }
  295. SubscribeToItems(newValue);
  296. }
  297. /// <summary>
  298. /// Called when the <see cref="INotifyCollectionChanged.CollectionChanged"/> event is
  299. /// raised on <see cref="Items"/>.
  300. /// </summary>
  301. /// <param name="sender">The event sender.</param>
  302. /// <param name="e">The event args.</param>
  303. protected virtual void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
  304. {
  305. UpdateItemCount();
  306. switch (e.Action)
  307. {
  308. case NotifyCollectionChangedAction.Add:
  309. AddControlItemsToLogicalChildren(e.NewItems);
  310. break;
  311. case NotifyCollectionChangedAction.Remove:
  312. RemoveControlItemsFromLogicalChildren(e.OldItems);
  313. break;
  314. }
  315. Presenter?.ItemsChanged(e);
  316. var collection = sender as ICollection;
  317. PseudoClasses.Set(":empty", collection == null || collection.Count == 0);
  318. PseudoClasses.Set(":singleitem", collection != null && collection.Count == 1);
  319. }
  320. /// <summary>
  321. /// Given a collection of items, adds those that are controls to the logical children.
  322. /// </summary>
  323. /// <param name="items">The items.</param>
  324. private void AddControlItemsToLogicalChildren(IEnumerable items)
  325. {
  326. var toAdd = new List<ILogical>();
  327. if (items != null)
  328. {
  329. foreach (var i in items)
  330. {
  331. var control = i as IControl;
  332. if (control != null && !LogicalChildren.Contains(control))
  333. {
  334. toAdd.Add(control);
  335. }
  336. }
  337. }
  338. LogicalChildren.AddRange(toAdd);
  339. }
  340. /// <summary>
  341. /// Given a collection of items, removes those that are controls to from logical children.
  342. /// </summary>
  343. /// <param name="items">The items.</param>
  344. private void RemoveControlItemsFromLogicalChildren(IEnumerable items)
  345. {
  346. var toRemove = new List<ILogical>();
  347. if (items != null)
  348. {
  349. foreach (var i in items)
  350. {
  351. var control = i as IControl;
  352. if (control != null)
  353. {
  354. toRemove.Add(control);
  355. }
  356. }
  357. }
  358. LogicalChildren.RemoveAll(toRemove);
  359. }
  360. /// <summary>
  361. /// Subscribes to an <see cref="Items"/> collection.
  362. /// </summary>
  363. /// <param name="items">The items collection.</param>
  364. private void SubscribeToItems(IEnumerable items)
  365. {
  366. PseudoClasses.Set(":empty", items == null || items.Count() == 0);
  367. PseudoClasses.Set(":singleitem", items != null && items.Count() == 1);
  368. var incc = items as INotifyCollectionChanged;
  369. if (incc != null)
  370. {
  371. _itemsCollectionChangedSubscription = incc.WeakSubscribe(ItemsCollectionChanged);
  372. }
  373. }
  374. /// <summary>
  375. /// Called when the <see cref="ItemTemplate"/> changes.
  376. /// </summary>
  377. /// <param name="e">The event args.</param>
  378. private void ItemTemplateChanged(AvaloniaPropertyChangedEventArgs e)
  379. {
  380. if (_itemContainerGenerator != null)
  381. {
  382. _itemContainerGenerator.ItemTemplate = (IDataTemplate)e.NewValue;
  383. // TODO: Rebuild the item containers.
  384. }
  385. }
  386. private void UpdateItemCount()
  387. {
  388. if (Items == null)
  389. {
  390. ItemCount = 0;
  391. }
  392. else if (Items is IList list)
  393. {
  394. ItemCount = list.Count;
  395. }
  396. else
  397. {
  398. ItemCount = Items.Count();
  399. }
  400. }
  401. protected static IInputElement GetNextControl(
  402. INavigableContainer container,
  403. NavigationDirection direction,
  404. IInputElement from,
  405. bool wrap)
  406. {
  407. IInputElement result;
  408. var c = from;
  409. do
  410. {
  411. result = container.GetControl(direction, c, wrap);
  412. from = from ?? result;
  413. if (result != null &&
  414. result.Focusable &&
  415. result.IsEffectivelyEnabled &&
  416. result.IsEffectivelyVisible)
  417. {
  418. return result;
  419. }
  420. c = result;
  421. } while (c != null && c != from);
  422. return null;
  423. }
  424. }
  425. }