TreeView.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.Specialized;
  5. using System.ComponentModel;
  6. using System.Diagnostics.CodeAnalysis;
  7. using System.Linq;
  8. using Avalonia.Collections;
  9. using Avalonia.Controls.Generators;
  10. using Avalonia.Controls.Primitives;
  11. using Avalonia.Input;
  12. using Avalonia.Input.Platform;
  13. using Avalonia.Interactivity;
  14. using Avalonia.Layout;
  15. using Avalonia.Threading;
  16. using Avalonia.VisualTree;
  17. namespace Avalonia.Controls
  18. {
  19. /// <summary>
  20. /// Displays a hierarchical tree of data.
  21. /// </summary>
  22. public class TreeView : ItemsControl, ICustomKeyboardNavigation
  23. {
  24. /// <summary>
  25. /// Defines the <see cref="AutoScrollToSelectedItem"/> property.
  26. /// </summary>
  27. public static readonly StyledProperty<bool> AutoScrollToSelectedItemProperty =
  28. SelectingItemsControl.AutoScrollToSelectedItemProperty.AddOwner<TreeView>();
  29. /// <summary>
  30. /// Defines the <see cref="SelectedItem"/> property.
  31. /// </summary>
  32. public static readonly DirectProperty<TreeView, object?> SelectedItemProperty =
  33. SelectingItemsControl.SelectedItemProperty.AddOwner<TreeView>(
  34. o => o.SelectedItem,
  35. (o, v) => o.SelectedItem = v);
  36. /// <summary>
  37. /// Defines the <see cref="SelectedItems"/> property.
  38. /// </summary>
  39. public static readonly DirectProperty<TreeView, IList> SelectedItemsProperty =
  40. AvaloniaProperty.RegisterDirect<TreeView, IList>(
  41. nameof(SelectedItems),
  42. o => o.SelectedItems,
  43. (o, v) => o.SelectedItems = v);
  44. /// <summary>
  45. /// Defines the <see cref="SelectionMode"/> property.
  46. /// </summary>
  47. public static readonly StyledProperty<SelectionMode> SelectionModeProperty =
  48. ListBox.SelectionModeProperty.AddOwner<TreeView>();
  49. private static readonly IList Empty = Array.Empty<object>();
  50. private object? _selectedItem;
  51. private IList? _selectedItems;
  52. private bool _syncingSelectedItems;
  53. /// <summary>
  54. /// Initializes static members of the <see cref="TreeView"/> class.
  55. /// </summary>
  56. static TreeView()
  57. {
  58. SelectingItemsControl.IsSelectedChangedEvent.AddClassHandler<TreeView>((x, e) =>
  59. x.ContainerSelectionChanged(e));
  60. }
  61. /// <summary>
  62. /// Occurs when the control's selection changes.
  63. /// </summary>
  64. public event EventHandler<SelectionChangedEventArgs>? SelectionChanged
  65. {
  66. add => AddHandler(SelectingItemsControl.SelectionChangedEvent, value);
  67. remove => RemoveHandler(SelectingItemsControl.SelectionChangedEvent, value);
  68. }
  69. /// <summary>
  70. /// Gets the <see cref="TreeItemContainerGenerator"/> for the tree view.
  71. /// </summary>
  72. public new TreeItemContainerGenerator ItemContainerGenerator =>
  73. (TreeItemContainerGenerator)base.ItemContainerGenerator;
  74. /// <summary>
  75. /// Gets or sets a value indicating whether to automatically scroll to newly selected items.
  76. /// </summary>
  77. public bool AutoScrollToSelectedItem
  78. {
  79. get => GetValue(AutoScrollToSelectedItemProperty);
  80. set => SetValue(AutoScrollToSelectedItemProperty, value);
  81. }
  82. /// <summary>
  83. /// Gets or sets the selection mode.
  84. /// </summary>
  85. public SelectionMode SelectionMode
  86. {
  87. get => GetValue(SelectionModeProperty);
  88. set => SetValue(SelectionModeProperty, value);
  89. }
  90. /// <summary>
  91. /// Gets or sets the selected item.
  92. /// </summary>
  93. /// <remarks>
  94. /// Note that setting this property only currently works if the item is expanded to be visible.
  95. /// To select non-expanded nodes use `Selection.SelectedIndex`.
  96. /// </remarks>
  97. public object? SelectedItem
  98. {
  99. get => _selectedItem;
  100. set
  101. {
  102. var selectedItems = SelectedItems;
  103. SetAndRaise(SelectedItemProperty, ref _selectedItem, value);
  104. if (value != null)
  105. {
  106. if (selectedItems.Count != 1 || selectedItems[0] != value)
  107. {
  108. SelectSingleItem(value);
  109. }
  110. }
  111. else if (SelectedItems.Count > 0)
  112. {
  113. SelectedItems.Clear();
  114. }
  115. }
  116. }
  117. /// <summary>
  118. /// Gets or sets the selected items.
  119. /// </summary>
  120. [AllowNull]
  121. public IList SelectedItems
  122. {
  123. get
  124. {
  125. if (_selectedItems == null)
  126. {
  127. _selectedItems = new AvaloniaList<object>();
  128. SubscribeToSelectedItems();
  129. }
  130. return _selectedItems;
  131. }
  132. set
  133. {
  134. if (value?.IsFixedSize == true || value?.IsReadOnly == true)
  135. {
  136. throw new NotSupportedException(
  137. "Cannot use a fixed size or read-only collection as SelectedItems.");
  138. }
  139. UnsubscribeFromSelectedItems();
  140. _selectedItems = value ?? new AvaloniaList<object>();
  141. SubscribeToSelectedItems();
  142. }
  143. }
  144. /// <summary>
  145. /// Expands the specified <see cref="TreeViewItem"/> all descendent <see cref="TreeViewItem"/>s.
  146. /// </summary>
  147. /// <param name="item">The item to expand.</param>
  148. public void ExpandSubTree(TreeViewItem item)
  149. {
  150. item.IsExpanded = true;
  151. if (item.Presenter?.Panel is null)
  152. (this.GetVisualRoot() as ILayoutRoot)?.LayoutManager.ExecuteLayoutPass();
  153. if (item.Presenter?.Panel is { } panel)
  154. {
  155. foreach (var child in panel.Children)
  156. {
  157. if (child is TreeViewItem treeViewItem)
  158. {
  159. ExpandSubTree(treeViewItem);
  160. }
  161. }
  162. }
  163. }
  164. /// <summary>
  165. /// Collapse the specified <see cref="TreeViewItem"/> all descendent <see cref="TreeViewItem"/> s.
  166. /// </summary>
  167. /// <param name="item">The item to collapse.</param>
  168. public void CollapseSubTree(TreeViewItem item)
  169. {
  170. item.IsExpanded = false;
  171. if (item.Presenter?.Panel != null)
  172. {
  173. foreach (var child in item.Presenter.Panel.Children)
  174. {
  175. if (child is TreeViewItem treeViewItem)
  176. {
  177. CollapseSubTree(treeViewItem);
  178. }
  179. }
  180. }
  181. }
  182. /// <summary>
  183. /// Selects all items in the <see cref="TreeView"/>.
  184. /// </summary>
  185. /// <remarks>
  186. /// Note that this method only selects nodes currently visible due to their parent nodes
  187. /// being expanded: it does not expand nodes.
  188. /// </remarks>
  189. public void SelectAll()
  190. {
  191. var allItems = new List<object>();
  192. void AddItems(ItemsControl itemsControl)
  193. {
  194. foreach (var item in itemsControl.ItemsView)
  195. allItems.Add(item!);
  196. foreach (var child in itemsControl.GetRealizedContainers())
  197. {
  198. if (child is ItemsControl childItemsControl)
  199. AddItems(childItemsControl);
  200. }
  201. }
  202. AddItems(this);
  203. SynchronizeItems(SelectedItems, allItems);
  204. }
  205. /// <summary>
  206. /// Deselects all items in the <see cref="TreeView"/>.
  207. /// </summary>
  208. public void UnselectAll()
  209. {
  210. SelectedItems.Clear();
  211. }
  212. public IEnumerable<Control> GetRealizedTreeContainers()
  213. {
  214. static IEnumerable<Control> GetRealizedContainers(ItemsControl itemsControl)
  215. {
  216. foreach (var container in itemsControl.GetRealizedContainers())
  217. {
  218. yield return container;
  219. if (container is ItemsControl itemsControlContainer)
  220. foreach (var child in GetRealizedContainers(itemsControlContainer))
  221. yield return child;
  222. }
  223. }
  224. return GetRealizedContainers(this);
  225. }
  226. public Control? TreeContainerFromItem(object item)
  227. {
  228. static Control? TreeContainerFromItem(ItemsControl itemsControl, object item)
  229. {
  230. if (itemsControl.ContainerFromItem(item) is { } container)
  231. return container;
  232. foreach (var child in itemsControl.GetRealizedContainers())
  233. {
  234. if (child is ItemsControl childItemsControl &&
  235. TreeContainerFromItem(childItemsControl, item) is { } childContainer)
  236. return childContainer;
  237. }
  238. return null;
  239. }
  240. return TreeContainerFromItem(this, item);
  241. }
  242. public object? TreeItemFromContainer(Control container)
  243. {
  244. static object? TreeItemFromContainer(ItemsControl itemsControl, Control container)
  245. {
  246. if (itemsControl.ItemFromContainer(container) is { } item)
  247. return item;
  248. foreach (var child in itemsControl.GetRealizedContainers())
  249. {
  250. if (child is ItemsControl childItemsControl &&
  251. TreeItemFromContainer(childItemsControl, container) is { } childContainer)
  252. return childContainer;
  253. }
  254. return null;
  255. }
  256. return TreeItemFromContainer(this, container);
  257. }
  258. private protected override void OnItemsViewCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
  259. {
  260. base.OnItemsViewCollectionChanged(sender, e);
  261. switch (e.Action)
  262. {
  263. case NotifyCollectionChangedAction.Remove:
  264. case NotifyCollectionChangedAction.Replace:
  265. foreach (var i in e.OldItems!)
  266. SelectedItems.Remove(i);
  267. break;
  268. case NotifyCollectionChangedAction.Reset:
  269. SelectedItems.Clear();
  270. break;
  271. }
  272. }
  273. /// <summary>
  274. /// Subscribes to the <see cref="SelectedItems"/> CollectionChanged event, if any.
  275. /// </summary>
  276. private void SubscribeToSelectedItems()
  277. {
  278. if (_selectedItems is INotifyCollectionChanged incc)
  279. {
  280. incc.CollectionChanged += SelectedItemsCollectionChanged;
  281. }
  282. SelectedItemsCollectionChanged(
  283. _selectedItems,
  284. new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  285. }
  286. private void SelectSingleItem(object item)
  287. {
  288. var oldValue = _selectedItem;
  289. _syncingSelectedItems = true;
  290. SelectedItems.Clear();
  291. _selectedItem = item;
  292. SelectedItems.Add(item);
  293. _syncingSelectedItems = false;
  294. RaisePropertyChanged(SelectedItemProperty, oldValue, _selectedItem);
  295. }
  296. /// <summary>
  297. /// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised.
  298. /// </summary>
  299. /// <param name="sender">The event sender.</param>
  300. /// <param name="e">The event args.</param>
  301. private void SelectedItemsCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
  302. {
  303. IList? added = null;
  304. IList? removed = null;
  305. switch (e.Action)
  306. {
  307. case NotifyCollectionChangedAction.Add:
  308. SelectedItemsAdded(e.NewItems!.Cast<object>().ToArray());
  309. if (AutoScrollToSelectedItem)
  310. {
  311. var container = ContainerFromItem(e.NewItems![0]!);
  312. container?.BringIntoView();
  313. }
  314. added = e.NewItems;
  315. break;
  316. case NotifyCollectionChangedAction.Remove:
  317. if (!_syncingSelectedItems)
  318. {
  319. if (SelectedItems.Count == 0)
  320. {
  321. SelectedItem = null;
  322. }
  323. else
  324. {
  325. var selectedIndex = SelectedItems.IndexOf(_selectedItem);
  326. if (selectedIndex == -1)
  327. {
  328. var old = _selectedItem;
  329. _selectedItem = SelectedItems[0];
  330. RaisePropertyChanged(SelectedItemProperty, old, _selectedItem);
  331. }
  332. }
  333. }
  334. foreach (var item in e.OldItems!)
  335. {
  336. MarkItemSelected(item, false);
  337. }
  338. removed = e.OldItems;
  339. break;
  340. case NotifyCollectionChangedAction.Reset:
  341. foreach (var container in GetRealizedTreeContainers())
  342. {
  343. MarkContainerSelected(container, false);
  344. }
  345. if (SelectedItems.Count > 0)
  346. {
  347. SelectedItemsAdded(SelectedItems);
  348. added = SelectedItems;
  349. }
  350. else if (!_syncingSelectedItems)
  351. {
  352. SelectedItem = null;
  353. }
  354. break;
  355. case NotifyCollectionChangedAction.Replace:
  356. foreach (var item in e.OldItems!)
  357. {
  358. MarkItemSelected(item, false);
  359. }
  360. foreach (var item in e.NewItems!)
  361. {
  362. MarkItemSelected(item, true);
  363. }
  364. if (SelectedItem != SelectedItems[0] && !_syncingSelectedItems)
  365. {
  366. var oldItem = SelectedItem;
  367. var item = SelectedItems[0];
  368. _selectedItem = item;
  369. RaisePropertyChanged(SelectedItemProperty, oldItem, item);
  370. }
  371. added = e.NewItems;
  372. removed = e.OldItems;
  373. break;
  374. }
  375. if (added?.Count > 0 || removed?.Count > 0)
  376. {
  377. var changed = new SelectionChangedEventArgs(
  378. SelectingItemsControl.SelectionChangedEvent,
  379. removed ?? Empty,
  380. added ?? Empty);
  381. RaiseEvent(changed);
  382. }
  383. }
  384. private void MarkItemSelected(object item, bool selected)
  385. {
  386. if (TreeContainerFromItem(item) is Control container)
  387. MarkContainerSelected(container, selected);
  388. }
  389. private void SelectedItemsAdded(IList items)
  390. {
  391. if (items.Count == 0)
  392. {
  393. return;
  394. }
  395. foreach (object item in items)
  396. {
  397. MarkItemSelected(item, true);
  398. }
  399. if (SelectedItem == null && !_syncingSelectedItems)
  400. {
  401. SetAndRaise(SelectedItemProperty, ref _selectedItem, items[0]);
  402. }
  403. }
  404. /// <summary>
  405. /// Unsubscribes from the <see cref="SelectedItems"/> CollectionChanged event, if any.
  406. /// </summary>
  407. private void UnsubscribeFromSelectedItems()
  408. {
  409. if (_selectedItems is INotifyCollectionChanged incc)
  410. {
  411. incc.CollectionChanged -= SelectedItemsCollectionChanged;
  412. }
  413. }
  414. (bool handled, IInputElement? next) ICustomKeyboardNavigation.GetNext(IInputElement element,
  415. NavigationDirection direction)
  416. {
  417. if (direction == NavigationDirection.Next || direction == NavigationDirection.Previous)
  418. {
  419. if (!this.IsVisualAncestorOf((Visual)element))
  420. {
  421. var result = _selectedItem != null ?
  422. TreeContainerFromItem(_selectedItem) :
  423. ContainerFromIndex(0);
  424. return (result != null, result); // SelectedItem may not be in the treeview.
  425. }
  426. return (true, null);
  427. }
  428. return (false, null);
  429. }
  430. protected internal override Control CreateContainerForItemOverride(object? item, int index, object? recycleKey)
  431. {
  432. return new TreeViewItem();
  433. }
  434. protected internal override bool NeedsContainerOverride(object? item, int index, out object? recycleKey)
  435. {
  436. return NeedsContainer<TreeViewItem>(item, out recycleKey);
  437. }
  438. protected internal override void ContainerForItemPreparedOverride(Control container, object? item, int index)
  439. {
  440. base.ContainerForItemPreparedOverride(container, item, index);
  441. // Once the container has been full prepared and added to the tree, any bindings from
  442. // styles or item container themes are guaranteed to be applied.
  443. if (container.IsSet(SelectingItemsControl.IsSelectedProperty))
  444. {
  445. // The IsSelected property is set on the container: there is a style or item
  446. // container theme which has bound the IsSelected property. Update our selection
  447. // based on the selection state of the container.
  448. var containerIsSelected = SelectingItemsControl.GetIsSelected(container);
  449. UpdateSelectionFromContainer(container, select: containerIsSelected, toggleModifier: true);
  450. }
  451. // The IsSelected property is not set on the container: update the container
  452. // selection based on the current selection as understood by this control.
  453. MarkContainerSelected(container, SelectedItems.Contains(item));
  454. }
  455. /// <inheritdoc/>
  456. protected override void OnGotFocus(GotFocusEventArgs e)
  457. {
  458. if (e.NavigationMethod == NavigationMethod.Directional)
  459. {
  460. e.Handled = UpdateSelectionFromEventSource(
  461. e.Source!,
  462. true,
  463. e.KeyModifiers.HasAllFlags(KeyModifiers.Shift));
  464. }
  465. }
  466. protected override void OnKeyDown(KeyEventArgs e)
  467. {
  468. var direction = e.Key.ToNavigationDirection();
  469. if (direction?.IsDirectional() == true && !e.Handled)
  470. {
  471. if (SelectedItem != null)
  472. {
  473. var next = GetContainerInDirection(
  474. GetContainerFromEventSource(e.Source!),
  475. direction.Value,
  476. true);
  477. if (next != null)
  478. {
  479. FocusManager.Instance?.Focus(next, NavigationMethod.Directional);
  480. e.Handled = true;
  481. }
  482. }
  483. else
  484. {
  485. SelectedItem = ItemsView[0];
  486. }
  487. }
  488. if (!e.Handled)
  489. {
  490. var keymap = AvaloniaLocator.Current.GetService<PlatformHotkeyConfiguration>();
  491. bool Match(List<KeyGesture>? gestures) => gestures?.Any(g => g.Matches(e)) ?? false;
  492. if (this.SelectionMode == SelectionMode.Multiple && Match(keymap?.SelectAll))
  493. {
  494. SelectAll();
  495. e.Handled = true;
  496. }
  497. }
  498. }
  499. private TreeViewItem? GetContainerInDirection(
  500. TreeViewItem? from,
  501. NavigationDirection direction,
  502. bool intoChildren)
  503. {
  504. var parentItemsControl = from?.Parent switch
  505. {
  506. TreeView tv => (ItemsControl)tv,
  507. TreeViewItem i => i,
  508. _ => null
  509. };
  510. if (parentItemsControl == null)
  511. {
  512. return null;
  513. }
  514. var index = from is not null ? parentItemsControl.IndexFromContainer(from) : -1;
  515. var parent = from?.Parent as ItemsControl;
  516. TreeViewItem? result = null;
  517. switch (direction)
  518. {
  519. case NavigationDirection.Up:
  520. if (index > 0)
  521. {
  522. var previous = (TreeViewItem)parentItemsControl.ContainerFromIndex(index - 1)!;
  523. result = previous.IsExpanded && previous.ItemCount > 0 ?
  524. (TreeViewItem)previous.ContainerFromIndex(previous.ItemCount - 1)! :
  525. previous;
  526. }
  527. else
  528. {
  529. result = from?.Parent as TreeViewItem;
  530. }
  531. break;
  532. case NavigationDirection.Down:
  533. case NavigationDirection.Right:
  534. if (from?.IsExpanded == true && intoChildren && from.ItemCount > 0)
  535. {
  536. result = (TreeViewItem)from.ContainerFromIndex(0)!;
  537. }
  538. else if (index < parent?.ItemCount - 1)
  539. {
  540. result = (TreeViewItem)parentItemsControl.ContainerFromIndex(index + 1)!;
  541. }
  542. else if (parent is TreeViewItem parentItem)
  543. {
  544. return GetContainerInDirection(parentItem, direction, false);
  545. }
  546. break;
  547. }
  548. return result;
  549. }
  550. /// <inheritdoc/>
  551. protected override void OnPointerPressed(PointerPressedEventArgs e)
  552. {
  553. base.OnPointerPressed(e);
  554. if (e.Source is Visual source)
  555. {
  556. var point = e.GetCurrentPoint(source);
  557. if (point.Properties.IsLeftButtonPressed || point.Properties.IsRightButtonPressed)
  558. {
  559. e.Handled = UpdateSelectionFromEventSource(
  560. e.Source,
  561. true,
  562. e.KeyModifiers.HasAllFlags(KeyModifiers.Shift),
  563. e.KeyModifiers.HasAllFlags(AvaloniaLocator.Current.GetRequiredService<PlatformHotkeyConfiguration>().CommandModifiers),
  564. point.Properties.IsRightButtonPressed);
  565. }
  566. }
  567. }
  568. /// <summary>
  569. /// Updates the selection for an item based on user interaction.
  570. /// </summary>
  571. /// <param name="container">The container.</param>
  572. /// <param name="select">Whether the item should be selected or unselected.</param>
  573. /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
  574. /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
  575. /// <param name="rightButton">Whether the event is a right-click.</param>
  576. protected void UpdateSelectionFromContainer(
  577. Control container,
  578. bool select = true,
  579. bool rangeModifier = false,
  580. bool toggleModifier = false,
  581. bool rightButton = false)
  582. {
  583. var item = TreeItemFromContainer(container);
  584. if (item == null)
  585. {
  586. return;
  587. }
  588. Control? selectedContainer = null;
  589. if (SelectedItem != null)
  590. {
  591. selectedContainer = TreeContainerFromItem(SelectedItem);
  592. }
  593. var mode = SelectionMode;
  594. var toggle = toggleModifier || mode.HasAllFlags(SelectionMode.Toggle);
  595. var multi = mode.HasAllFlags(SelectionMode.Multiple);
  596. var range = multi && rangeModifier && selectedContainer != null;
  597. if (!select)
  598. {
  599. SelectedItems.Remove(item);
  600. }
  601. else if (rightButton)
  602. {
  603. if (!SelectedItems.Contains(item))
  604. {
  605. SelectSingleItem(item);
  606. }
  607. }
  608. else if (!toggle && !range)
  609. {
  610. SelectSingleItem(item);
  611. }
  612. else if (multi && range)
  613. {
  614. SynchronizeItems(
  615. SelectedItems,
  616. GetItemsInRange(selectedContainer as TreeViewItem, container as TreeViewItem));
  617. }
  618. else
  619. {
  620. var i = SelectedItems.IndexOf(item);
  621. if (i != -1)
  622. {
  623. SelectedItems.Remove(item);
  624. }
  625. else
  626. {
  627. if (multi)
  628. {
  629. SelectedItems.Add(item);
  630. }
  631. else
  632. {
  633. SelectedItem = item;
  634. }
  635. }
  636. }
  637. }
  638. [Obsolete, EditorBrowsable(EditorBrowsableState.Never)]
  639. private protected override ItemContainerGenerator CreateItemContainerGenerator()
  640. {
  641. return new TreeItemContainerGenerator(this);
  642. }
  643. /// <summary>
  644. /// Find which node is first in hierarchy.
  645. /// </summary>
  646. /// <param name="treeView">Search root.</param>
  647. /// <param name="nodeA">Nodes to find.</param>
  648. /// <param name="nodeB">Node to find.</param>
  649. /// <returns>Found first node.</returns>
  650. private static TreeViewItem? FindFirstNode(TreeView treeView, TreeViewItem nodeA, TreeViewItem nodeB)
  651. {
  652. return FindInContainers(treeView, nodeA, nodeB);
  653. }
  654. private static TreeViewItem? FindInContainers(ItemsControl itemsControl,
  655. TreeViewItem nodeA,
  656. TreeViewItem nodeB)
  657. {
  658. foreach (var container in itemsControl.GetRealizedContainers())
  659. {
  660. TreeViewItem? node = FindFirstNode(container as TreeViewItem, nodeA, nodeB);
  661. if (node != null)
  662. {
  663. return node;
  664. }
  665. }
  666. return null;
  667. }
  668. private static TreeViewItem? FindFirstNode(TreeViewItem? node, TreeViewItem nodeA, TreeViewItem nodeB)
  669. {
  670. if (node == null)
  671. {
  672. return null;
  673. }
  674. TreeViewItem? match = node == nodeA ? nodeA : node == nodeB ? nodeB : null;
  675. if (match != null)
  676. {
  677. return match;
  678. }
  679. return FindInContainers(node, nodeA, nodeB);
  680. }
  681. /// <summary>
  682. /// Returns all items that belong to containers between <paramref name="from"/> and <paramref name="to"/>.
  683. /// The range is inclusive.
  684. /// </summary>
  685. /// <param name="from">From container.</param>
  686. /// <param name="to">To container.</param>
  687. private List<object> GetItemsInRange(TreeViewItem? from, TreeViewItem? to)
  688. {
  689. var items = new List<object>();
  690. if (from == null || to == null)
  691. {
  692. return items;
  693. }
  694. TreeViewItem? firstItem = FindFirstNode(this, from, to);
  695. if (firstItem == null)
  696. {
  697. return items;
  698. }
  699. bool wasReversed = false;
  700. if (firstItem == to)
  701. {
  702. var temp = from;
  703. from = to;
  704. to = temp;
  705. wasReversed = true;
  706. }
  707. TreeViewItem? node = from;
  708. while (node is not null && node != to)
  709. {
  710. var item = TreeItemFromContainer(node);
  711. if (item != null)
  712. {
  713. items.Add(item);
  714. }
  715. node = GetContainerInDirection(node, NavigationDirection.Down, true);
  716. }
  717. var toItem = TreeItemFromContainer(to);
  718. if (toItem != null)
  719. {
  720. items.Add(toItem);
  721. }
  722. if (wasReversed)
  723. {
  724. items.Reverse();
  725. }
  726. return items;
  727. }
  728. /// <summary>
  729. /// Updates the selection based on an event that may have originated in a container that
  730. /// belongs to the control.
  731. /// </summary>
  732. /// <param name="eventSource">The control that raised the event.</param>
  733. /// <param name="select">Whether the container should be selected or unselected.</param>
  734. /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param>
  735. /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param>
  736. /// <param name="rightButton">Whether the event is a right-click.</param>
  737. /// <returns>
  738. /// True if the event originated from a container that belongs to the control; otherwise
  739. /// false.
  740. /// </returns>
  741. protected bool UpdateSelectionFromEventSource(
  742. object eventSource,
  743. bool select = true,
  744. bool rangeModifier = false,
  745. bool toggleModifier = false,
  746. bool rightButton = false)
  747. {
  748. var container = GetContainerFromEventSource(eventSource);
  749. if (container != null)
  750. {
  751. UpdateSelectionFromContainer(container, select, rangeModifier, toggleModifier, rightButton);
  752. return true;
  753. }
  754. return false;
  755. }
  756. /// <summary>
  757. /// Tries to get the container that was the source of an event.
  758. /// </summary>
  759. /// <param name="eventSource">The control that raised the event.</param>
  760. /// <returns>The container or null if the event did not originate in a container.</returns>
  761. protected TreeViewItem? GetContainerFromEventSource(object eventSource)
  762. {
  763. var item = ((Visual)eventSource).GetSelfAndVisualAncestors()
  764. .OfType<TreeViewItem>()
  765. .FirstOrDefault();
  766. return item?.TreeViewOwner == this ? item : null;
  767. }
  768. /// <summary>
  769. /// Called when a container raises the
  770. /// <see cref="SelectingItemsControl.IsSelectedChangedEvent"/>.
  771. /// </summary>
  772. /// <param name="e">The event.</param>
  773. private void ContainerSelectionChanged(RoutedEventArgs e)
  774. {
  775. if (e.Source is TreeViewItem container &&
  776. container.TreeViewOwner == this &&
  777. TreeItemFromContainer(container) is object item)
  778. {
  779. var containerIsSelected = SelectingItemsControl.GetIsSelected(container);
  780. var ourIsSelected = SelectedItems.Contains(item);
  781. if (containerIsSelected != ourIsSelected)
  782. {
  783. if (containerIsSelected)
  784. SelectedItems.Add(item);
  785. else
  786. SelectedItems.Remove(item);
  787. }
  788. }
  789. if (e.Source != this)
  790. {
  791. e.Handled = true;
  792. }
  793. }
  794. /// <summary>
  795. /// Sets a container's 'selected' class or <see cref="ISelectable.IsSelected"/>.
  796. /// </summary>
  797. /// <param name="container">The container.</param>
  798. /// <param name="selected">Whether the control is selected</param>
  799. private void MarkContainerSelected(Control container, bool selected)
  800. {
  801. container.SetCurrentValue(SelectingItemsControl.IsSelectedProperty, selected);
  802. }
  803. /// <summary>
  804. /// Makes a list of objects equal another (though doesn't preserve order).
  805. /// </summary>
  806. /// <param name="items">The items collection.</param>
  807. /// <param name="desired">The desired items.</param>
  808. private static void SynchronizeItems(IList items, IEnumerable<object> desired)
  809. {
  810. var list = items.Cast<object>();
  811. var toRemove = list.Except(desired).ToList();
  812. var toAdd = desired.Except(list).ToList();
  813. foreach (var i in toRemove)
  814. {
  815. items.Remove(i);
  816. }
  817. foreach (var i in toAdd)
  818. {
  819. items.Add(i);
  820. }
  821. }
  822. }
  823. }