ListBoxTests.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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.ObjectModel;
  5. using System.Linq;
  6. using Avalonia.Controls.Presenters;
  7. using Avalonia.Controls.Templates;
  8. using Avalonia.Data;
  9. using Avalonia.LogicalTree;
  10. using Avalonia.Styling;
  11. using Avalonia.UnitTests;
  12. using Avalonia.VisualTree;
  13. using Xunit;
  14. namespace Avalonia.Controls.UnitTests
  15. {
  16. public class ListBoxTests
  17. {
  18. [Fact]
  19. public void Should_Use_ItemTemplate_To_Create_Item_Content()
  20. {
  21. var target = new ListBox
  22. {
  23. Template = ListBoxTemplate(),
  24. Items = new[] { "Foo" },
  25. ItemTemplate = new FuncDataTemplate<string>(_ => new Canvas()),
  26. };
  27. Prepare(target);
  28. var container = (ListBoxItem)target.Presenter.Panel.Children[0];
  29. Assert.IsType<Canvas>(container.Presenter.Child);
  30. }
  31. [Fact]
  32. public void ListBox_Should_Find_ItemsPresenter_In_ScrollViewer()
  33. {
  34. var target = new ListBox
  35. {
  36. Template = ListBoxTemplate(),
  37. };
  38. Prepare(target);
  39. Assert.IsType<ItemsPresenter>(target.Presenter);
  40. }
  41. [Fact]
  42. public void ListBoxItem_Containers_Should_Be_Generated()
  43. {
  44. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  45. {
  46. var items = new[] { "Foo", "Bar", "Baz " };
  47. var target = new ListBox
  48. {
  49. Template = ListBoxTemplate(),
  50. Items = items,
  51. };
  52. Prepare(target);
  53. var text = target.Presenter.Panel.Children
  54. .OfType<ListBoxItem>()
  55. .Select(x => x.Presenter.Child)
  56. .OfType<TextBlock>()
  57. .Select(x => x.Text)
  58. .ToList();
  59. Assert.Equal(items, text);
  60. }
  61. }
  62. [Fact]
  63. public void LogicalChildren_Should_Be_Set_For_DataTemplate_Generated_Items()
  64. {
  65. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  66. {
  67. var target = new ListBox
  68. {
  69. Template = ListBoxTemplate(),
  70. Items = new[] { "Foo", "Bar", "Baz " },
  71. };
  72. Prepare(target);
  73. Assert.Equal(3, target.GetLogicalChildren().Count());
  74. foreach (var child in target.GetLogicalChildren())
  75. {
  76. Assert.IsType<ListBoxItem>(child);
  77. }
  78. }
  79. }
  80. [Fact]
  81. public void DataContexts_Should_Be_Correctly_Set()
  82. {
  83. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  84. {
  85. var items = new object[]
  86. {
  87. "Foo",
  88. new Item("Bar"),
  89. new TextBlock { Text = "Baz" },
  90. new ListBoxItem { Content = "Qux" },
  91. };
  92. var target = new ListBox
  93. {
  94. Template = ListBoxTemplate(),
  95. DataContext = "Base",
  96. DataTemplates =
  97. {
  98. new FuncDataTemplate<Item>(x => new Button { Content = x })
  99. },
  100. Items = items,
  101. };
  102. Prepare(target);
  103. var dataContexts = target.Presenter.Panel.Children
  104. .Cast<Control>()
  105. .Select(x => x.DataContext)
  106. .ToList();
  107. Assert.Equal(
  108. new object[] { items[0], items[1], "Base", "Base" },
  109. dataContexts);
  110. }
  111. }
  112. [Fact]
  113. public void Selection_Should_Be_Cleared_On_Recycled_Items()
  114. {
  115. var target = new ListBox
  116. {
  117. Template = ListBoxTemplate(),
  118. Items = Enumerable.Range(0, 20).Select(x => $"Item {x}").ToList(),
  119. ItemTemplate = new FuncDataTemplate<string>(x => new TextBlock { Height = 10 }),
  120. SelectedIndex = 0,
  121. };
  122. Prepare(target);
  123. // Make sure we're virtualized and first item is selected.
  124. Assert.Equal(10, target.Presenter.Panel.Children.Count);
  125. Assert.True(((ListBoxItem)target.Presenter.Panel.Children[0]).IsSelected);
  126. // Scroll down a page.
  127. target.Scroll.Offset = new Vector(0, 10);
  128. // Make sure recycled item isn't now selected.
  129. Assert.False(((ListBoxItem)target.Presenter.Panel.Children[0]).IsSelected);
  130. }
  131. [Fact]
  132. public void ScrollViewer_Should_Have_Correct_Extent_And_Viewport()
  133. {
  134. var target = new ListBox
  135. {
  136. Template = ListBoxTemplate(),
  137. Items = Enumerable.Range(0, 20).Select(x => $"Item {x}").ToList(),
  138. ItemTemplate = new FuncDataTemplate<string>(x => new TextBlock { Width = 20, Height = 10 }),
  139. SelectedIndex = 0,
  140. };
  141. Prepare(target);
  142. Assert.Equal(new Size(20, 20), target.Scroll.Extent);
  143. Assert.Equal(new Size(100, 10), target.Scroll.Viewport);
  144. }
  145. [Theory]
  146. [InlineData(ItemVirtualizationMode.Simple)]
  147. [InlineData(ItemVirtualizationMode.None)]
  148. public void When_Added_Removed_AfterItems_Reset_Should_Work(ItemVirtualizationMode virtMode)
  149. {
  150. using (UnitTestApplication.Start(TestServices.StyledWindow))
  151. {
  152. var items = new ObservableCollection<string>();
  153. void create()
  154. {
  155. foreach (var i in Enumerable.Range(1, 7))
  156. {
  157. items.Add(i.ToString());
  158. }
  159. }
  160. create();
  161. var wnd = new Window() { SizeToContent = SizeToContent.WidthAndHeight };
  162. wnd.IsVisible = true;
  163. var target = new ListBox() { VirtualizationMode = virtMode };
  164. wnd.Content = target;
  165. var lm = wnd.LayoutManager;
  166. target.Height = 110;//working fine when <=106 or >=119
  167. target.Width = 50;
  168. target.ItemTemplate = new FuncDataTemplate<object>(c =>
  169. {
  170. var tb = new TextBlock() { Height = 10, Width = 30 };
  171. tb.Bind(TextBlock.TextProperty, new Binding());
  172. return tb;
  173. }, true);
  174. target.DataContext = items;
  175. lm.ExecuteInitialLayoutPass(wnd);
  176. target.Bind(ItemsControl.ItemsProperty, new Binding());
  177. lm.ExecuteLayoutPass();
  178. var panel = target.Presenter.Panel;
  179. string itemsToString() =>
  180. string.Join(",", panel.Children.OfType<ListBoxItem>().Select(l => l.Content.ToString()).ToArray());
  181. void addafter(string item, string newitem)
  182. {
  183. items.Insert(items.IndexOf(item) + 1, newitem);
  184. lm.ExecuteLayoutPass();
  185. }
  186. void remove(string item)
  187. {
  188. items.Remove(item);
  189. lm.ExecuteLayoutPass();
  190. }
  191. addafter("1", "1+");//expected 1,1+,2,3,4,5,6,7
  192. addafter("2", "2+");//expected 1,1+,2,2+,3,4,5,6
  193. remove("2+");//expected 1,1+,2,3,4,5,6,7
  194. //Reset items
  195. items.Clear();
  196. create();
  197. addafter("1", "1+");//expected 1,1+,2,3,4,5,6,7
  198. addafter("2", "2+");//expected 1,1+,2,2+,3,4,5,6
  199. remove("2+");//expected 1,1+,2,3,4,5,6,7
  200. var sti = itemsToString();
  201. var lbItems = panel.Children.OfType<ListBoxItem>().ToArray();
  202. Assert.Equal("1", lbItems[0].Content);
  203. Assert.Equal("1+", lbItems[1].Content);
  204. Assert.Equal("2", lbItems[2].Content);
  205. Assert.Equal("3", lbItems[3].Content); //bug it's 2+ instead
  206. Assert.Equal("4", lbItems[4].Content);
  207. int lbi = 0;
  208. //ensure all items are fine
  209. foreach (var lb in lbItems)
  210. {
  211. Assert.Equal(items[lbi++], lb.Content);
  212. }
  213. //Assert.Equal("1,1+,2,3,4,5,6,7", sti);
  214. }
  215. }
  216. private FuncControlTemplate ListBoxTemplate()
  217. {
  218. return new FuncControlTemplate<ListBox>(parent =>
  219. new ScrollViewer
  220. {
  221. Name = "PART_ScrollViewer",
  222. Template = ScrollViewerTemplate(),
  223. Content = new ItemsPresenter
  224. {
  225. Name = "PART_ItemsPresenter",
  226. [~ItemsPresenter.ItemsProperty] = parent.GetObservable(ItemsControl.ItemsProperty).ToBinding(),
  227. [~ItemsPresenter.ItemsPanelProperty] = parent.GetObservable(ItemsControl.ItemsPanelProperty).ToBinding(),
  228. [~ItemsPresenter.VirtualizationModeProperty] = parent.GetObservable(ListBox.VirtualizationModeProperty).ToBinding(),
  229. }
  230. });
  231. }
  232. private FuncControlTemplate ListBoxItemTemplate()
  233. {
  234. return new FuncControlTemplate<ListBoxItem>(parent =>
  235. new ContentPresenter
  236. {
  237. Name = "PART_ContentPresenter",
  238. [!ContentPresenter.ContentProperty] = parent[!ListBoxItem.ContentProperty],
  239. [!ContentPresenter.ContentTemplateProperty] = parent[!ListBoxItem.ContentTemplateProperty],
  240. });
  241. }
  242. private FuncControlTemplate ScrollViewerTemplate()
  243. {
  244. return new FuncControlTemplate<ScrollViewer>(parent =>
  245. new ScrollContentPresenter
  246. {
  247. Name = "PART_ContentPresenter",
  248. [~ScrollContentPresenter.ContentProperty] = parent.GetObservable(ScrollViewer.ContentProperty).ToBinding(),
  249. [~~ScrollContentPresenter.ExtentProperty] = parent[~~ScrollViewer.ExtentProperty],
  250. [~~ScrollContentPresenter.OffsetProperty] = parent[~~ScrollViewer.OffsetProperty],
  251. [~~ScrollContentPresenter.ViewportProperty] = parent[~~ScrollViewer.ViewportProperty],
  252. });
  253. }
  254. private void Prepare(ListBox target)
  255. {
  256. // The ListBox needs to be part of a rooted visual tree.
  257. var root = new TestRoot();
  258. root.Child = target;
  259. // Apply the template to the ListBox itself.
  260. target.ApplyTemplate();
  261. // Then to its inner ScrollViewer.
  262. var scrollViewer = (ScrollViewer)target.GetVisualChildren().Single();
  263. scrollViewer.ApplyTemplate();
  264. // Then make the ScrollViewer create its child.
  265. ((ContentPresenter)scrollViewer.Presenter).UpdateChild();
  266. // Now the ItemsPresenter should be reigstered, so apply its template.
  267. target.Presenter.ApplyTemplate();
  268. // Because ListBox items are virtualized we need to do a layout to make them appear.
  269. target.Measure(new Size(100, 100));
  270. target.Arrange(new Rect(0, 0, 100, 100));
  271. // Now set and apply the item templates.
  272. foreach (ListBoxItem item in target.Presenter.Panel.Children)
  273. {
  274. item.Template = ListBoxItemTemplate();
  275. item.ApplyTemplate();
  276. item.Presenter.ApplyTemplate();
  277. ((ContentPresenter)item.Presenter).UpdateChild();
  278. }
  279. // The items were created before the template was applied, so now we need to go back
  280. // and re-arrange everything.
  281. foreach (IControl i in target.GetSelfAndVisualDescendants())
  282. {
  283. i.InvalidateMeasure();
  284. }
  285. target.Measure(new Size(100, 100));
  286. target.Arrange(new Rect(0, 0, 100, 100));
  287. }
  288. private class Item
  289. {
  290. public Item(string value)
  291. {
  292. Value = value;
  293. }
  294. public string Value { get; }
  295. }
  296. }
  297. }