1
0

ListBoxTests.cs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Collections.ObjectModel;
  5. using System.Collections.Specialized;
  6. using System.Linq;
  7. using System.Reactive.Subjects;
  8. using Avalonia.Collections;
  9. using Avalonia.Controls.Presenters;
  10. using Avalonia.Controls.Primitives;
  11. using Avalonia.Controls.Templates;
  12. using Avalonia.Data;
  13. using Avalonia.Input;
  14. using Avalonia.Layout;
  15. using Avalonia.LogicalTree;
  16. using Avalonia.Markup.Xaml.Templates;
  17. using Avalonia.Styling;
  18. using Avalonia.UnitTests;
  19. using Avalonia.VisualTree;
  20. using Xunit;
  21. namespace Avalonia.Controls.UnitTests
  22. {
  23. public class ListBoxTests : ScopedTestBase
  24. {
  25. private MouseTestHelper _mouse = new MouseTestHelper();
  26. [Fact]
  27. public void Should_Use_ItemTemplate_To_Create_Item_Content()
  28. {
  29. var target = new ListBox
  30. {
  31. Template = ListBoxTemplate(),
  32. ItemsSource = new[] { "Foo" },
  33. ItemTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()),
  34. };
  35. Prepare(target);
  36. var container = (ListBoxItem)target.Presenter.Panel.Children[0];
  37. Assert.IsType<Canvas>(container.Presenter.Child);
  38. }
  39. [Fact]
  40. public void ListBox_Should_Find_ItemsPresenter_In_ScrollViewer()
  41. {
  42. var target = new ListBox
  43. {
  44. Template = ListBoxTemplate(),
  45. };
  46. Prepare(target);
  47. Assert.IsType<ItemsPresenter>(target.Presenter);
  48. }
  49. [Fact]
  50. public void ListBox_Should_Find_Scrollviewer_In_Template()
  51. {
  52. var target = new ListBox
  53. {
  54. Template = ListBoxTemplate(),
  55. };
  56. ScrollViewer viewer = null;
  57. target.TemplateApplied += (sender, e) =>
  58. {
  59. viewer = target.Scroll as ScrollViewer;
  60. };
  61. Prepare(target);
  62. Assert.NotNull(viewer);
  63. }
  64. [Fact]
  65. public void ListBoxItem_Containers_Should_Be_Generated()
  66. {
  67. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  68. {
  69. var items = new[] { "Foo", "Bar", "Baz " };
  70. var target = new ListBox
  71. {
  72. Template = ListBoxTemplate(),
  73. ItemsSource = items,
  74. };
  75. Prepare(target);
  76. var text = target.Presenter.Panel.Children
  77. .OfType<ListBoxItem>()
  78. .Select(x => x.Presenter.Child)
  79. .OfType<TextBlock>()
  80. .Select(x => x.Text)
  81. .ToList();
  82. Assert.Equal(items, text);
  83. }
  84. }
  85. [Fact]
  86. public void Container_Should_Have_Theme_Set_To_ItemContainerTheme()
  87. {
  88. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  89. {
  90. var items = new[] { "Foo", "Bar", "Baz " };
  91. var theme = new ControlTheme(typeof(ListBoxItem));
  92. var target = new ListBox
  93. {
  94. Template = ListBoxTemplate(),
  95. ItemsSource = items,
  96. ItemContainerTheme = theme,
  97. };
  98. Prepare(target);
  99. var container = (ListBoxItem)target.Presenter.Panel.Children[0];
  100. Assert.Same(container.Theme, theme);
  101. }
  102. }
  103. [Fact]
  104. public void Inline_Item_Should_Have_Theme_Set_To_ItemContainerTheme()
  105. {
  106. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  107. {
  108. var theme = new ControlTheme(typeof(ListBoxItem));
  109. var target = new ListBox
  110. {
  111. Template = ListBoxTemplate(),
  112. Items = { new ListBoxItem() },
  113. ItemContainerTheme = theme,
  114. };
  115. Prepare(target);
  116. var container = (ListBoxItem)target.Presenter.Panel.Children[0];
  117. Assert.Same(container.Theme, theme);
  118. }
  119. }
  120. [Fact]
  121. public void LogicalChildren_Should_Be_Set_For_DataTemplate_Generated_Items()
  122. {
  123. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  124. {
  125. var target = new ListBox
  126. {
  127. Template = ListBoxTemplate(),
  128. ItemsSource = new[] { "Foo", "Bar", "Baz " },
  129. };
  130. Prepare(target);
  131. Assert.Equal(3, target.GetLogicalChildren().Count());
  132. foreach (var child in target.GetLogicalChildren())
  133. {
  134. Assert.IsType<ListBoxItem>(child);
  135. }
  136. }
  137. }
  138. [Fact]
  139. public void DataContexts_Should_Be_Correctly_Set()
  140. {
  141. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  142. {
  143. var items = new object[]
  144. {
  145. "Foo",
  146. new Item("Bar"),
  147. new TextBlock { Text = "Baz" },
  148. new ListBoxItem { Content = "Qux" },
  149. };
  150. var target = new ListBox
  151. {
  152. Template = ListBoxTemplate(),
  153. DataContext = "Base",
  154. ItemTemplate = new FuncDataTemplate<Item>((x, _) => new Button { Content = x }),
  155. ItemsSource = items,
  156. };
  157. Prepare(target);
  158. var dataContexts = target.Presenter.Panel.Children
  159. .Cast<Control>()
  160. .Select(x => x.DataContext)
  161. .ToList();
  162. Assert.Equal(
  163. new object[] { items[0], items[1], "Base", "Base" },
  164. dataContexts);
  165. }
  166. }
  167. [Fact]
  168. public void Selection_Should_Be_Cleared_On_Recycled_Items()
  169. {
  170. using (UnitTestApplication.Start(TestServices.StyledWindow))
  171. {
  172. var target = new ListBox
  173. {
  174. Template = ListBoxTemplate(),
  175. ItemsSource = Enumerable.Range(0, 20).Select(x => $"Item {x}").ToList(),
  176. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 }),
  177. SelectedIndex = 0,
  178. };
  179. Prepare(target);
  180. // Make sure we're virtualized and first item is selected.
  181. Assert.Equal(10, target.Presenter.Panel.Children.Count);
  182. Assert.True(((ListBoxItem)target.Presenter.Panel.Children[0]).IsSelected);
  183. // The selected item must not be the anchor, otherwise it won't get recycled.
  184. target.Selection.AnchorIndex = -1;
  185. // Scroll down a page.
  186. target.Scroll.Offset = new Vector(0, 10);
  187. Layout(target);
  188. // Make sure recycled item isn't now selected.
  189. Assert.False(((ListBoxItem)target.Presenter.Panel.Children[0]).IsSelected);
  190. }
  191. }
  192. [Fact]
  193. public void ScrollViewer_Should_Have_Correct_Extent_And_Viewport()
  194. {
  195. using (UnitTestApplication.Start(TestServices.StyledWindow))
  196. {
  197. var target = new ListBox
  198. {
  199. Template = ListBoxTemplate(),
  200. ItemsSource = Enumerable.Range(0, 20).Select(x => $"Item {x}").ToList(),
  201. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
  202. SelectedIndex = 0,
  203. };
  204. Prepare(target);
  205. Assert.Equal(new Size(100, 200), target.Scroll.Extent);
  206. Assert.Equal(new Size(100, 100), target.Scroll.Viewport);
  207. }
  208. }
  209. [Fact]
  210. public void Containers_Correct_After_Clear_Add_Remove()
  211. {
  212. using (UnitTestApplication.Start(TestServices.StyledWindow))
  213. {
  214. // Issue #1936
  215. var items = new AvaloniaList<string>(Enumerable.Range(0, 11).Select(x => $"Item {x}"));
  216. var target = new ListBox
  217. {
  218. Template = ListBoxTemplate(),
  219. ItemsSource = items,
  220. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
  221. SelectedIndex = 0,
  222. };
  223. Prepare(target);
  224. items.Clear();
  225. items.AddRange(Enumerable.Range(0, 11).Select(x => $"Item {x}"));
  226. Layout(target);
  227. items.Remove("Item 2");
  228. Layout(target);
  229. var actual = target.GetRealizedContainers().Cast<ListBoxItem>().Select(x => (string)x.Content).ToList();
  230. Assert.Equal(items.OrderBy(x => x), actual.OrderBy(x => x));
  231. }
  232. }
  233. [Fact]
  234. public void Toggle_Selection_Should_Update_Containers()
  235. {
  236. using (UnitTestApplication.Start(TestServices.StyledWindow))
  237. {
  238. var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToArray();
  239. var target = new ListBox
  240. {
  241. Template = ListBoxTemplate(),
  242. ItemsSource = items,
  243. SelectionMode = SelectionMode.Toggle,
  244. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 })
  245. };
  246. Prepare(target);
  247. var lbItems = target.GetLogicalChildren().OfType<ListBoxItem>().ToArray();
  248. var item = lbItems[0];
  249. Assert.Equal(false, item.IsSelected);
  250. RaisePressedEvent(item, MouseButton.Left);
  251. Assert.Equal(true, item.IsSelected);
  252. RaisePressedEvent(item, MouseButton.Left);
  253. Assert.Equal(false, item.IsSelected);
  254. }
  255. }
  256. [Fact]
  257. public void Can_Decrease_Number_Of_Materialized_Items_By_Removing_From_Source_Collection()
  258. {
  259. using (UnitTestApplication.Start(TestServices.StyledWindow))
  260. {
  261. var items = new AvaloniaList<string>(Enumerable.Range(0, 20).Select(x => $"Item {x}"));
  262. var target = new ListBox
  263. {
  264. Template = ListBoxTemplate(),
  265. ItemsSource = items,
  266. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 })
  267. };
  268. Prepare(target);
  269. target.Scroll.Offset = new Vector(0, 1);
  270. items.RemoveRange(0, 11);
  271. }
  272. }
  273. private void RaisePressedEvent(ListBoxItem item, MouseButton mouseButton)
  274. {
  275. _mouse.Click(item, item, mouseButton);
  276. }
  277. [Fact]
  278. public void LayoutManager_Should_Measure_Arrange_All()
  279. {
  280. using (UnitTestApplication.Start(TestServices.StyledWindow))
  281. {
  282. var items = new AvaloniaList<string>(Enumerable.Range(1, 7).Select(v => v.ToString()));
  283. var wnd = new Window() { SizeToContent = SizeToContent.WidthAndHeight };
  284. wnd.IsVisible = true;
  285. var target = new ListBox();
  286. wnd.Content = target;
  287. var lm = wnd.LayoutManager;
  288. target.Height = 110;
  289. target.Width = 50;
  290. target.DataContext = items;
  291. target.ItemTemplate = new FuncDataTemplate<object>((c, _) =>
  292. {
  293. var tb = new TextBlock() { Height = 10, Width = 30 };
  294. tb.Bind(TextBlock.TextProperty, new Data.Binding());
  295. return tb;
  296. }, true);
  297. lm.ExecuteInitialLayoutPass();
  298. target.ItemsSource = items;
  299. lm.ExecuteLayoutPass();
  300. items.Insert(3, "3+");
  301. lm.ExecuteLayoutPass();
  302. items.Insert(4, "4+");
  303. lm.ExecuteLayoutPass();
  304. //RESET
  305. items.Clear();
  306. foreach (var i in Enumerable.Range(1, 7))
  307. {
  308. items.Add(i.ToString());
  309. }
  310. //working bit better with this line no outof memory or remaining to arrange/measure ???
  311. //lm.ExecuteLayoutPass();
  312. items.Insert(2, "2+");
  313. lm.ExecuteLayoutPass();
  314. //after few more layout cycles layoutmanager shouldn't hold any more visual for measure/arrange
  315. lm.ExecuteLayoutPass();
  316. lm.ExecuteLayoutPass();
  317. var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
  318. var toMeasure = lm.GetType().GetField("_toMeasure", flags).GetValue(lm) as System.Collections.Generic.IEnumerable<Layout.Layoutable>;
  319. var toArrange = lm.GetType().GetField("_toArrange", flags).GetValue(lm) as System.Collections.Generic.IEnumerable<Layout.Layoutable>;
  320. Assert.Equal(0, toMeasure.Count());
  321. Assert.Equal(0, toArrange.Count());
  322. }
  323. }
  324. [Fact]
  325. public void ListBox_Should_Be_Valid_After_Remove_Of_Item_In_NonVisibleArea()
  326. {
  327. using (UnitTestApplication.Start(TestServices.StyledWindow))
  328. {
  329. var items = new AvaloniaList<string>(Enumerable.Range(1, 30).Select(v => v.ToString()));
  330. var wnd = new Window() { Width = 100, Height = 100, IsVisible = true };
  331. var target = new ListBox()
  332. {
  333. AutoScrollToSelectedItem = true,
  334. Height = 100,
  335. Width = 50,
  336. ItemTemplate = new FuncDataTemplate<object>((c, _) => new Border() { Height = 10 }),
  337. ItemsSource = items,
  338. };
  339. wnd.Content = target;
  340. var lm = wnd.LayoutManager;
  341. lm.ExecuteInitialLayoutPass();
  342. //select last / scroll to last item
  343. target.SelectedItem = items.Last();
  344. lm.ExecuteLayoutPass();
  345. //remove the first item (in non realized area of the listbox)
  346. items.Remove("1");
  347. lm.ExecuteLayoutPass();
  348. Threading.Dispatcher.UIThread.RunJobs();
  349. Assert.Equal("30", target.ContainerFromIndex(items.Count - 1).DataContext);
  350. Assert.Equal("29", target.ContainerFromIndex(items.Count - 2).DataContext);
  351. Assert.Equal("28", target.ContainerFromIndex(items.Count - 3).DataContext);
  352. Assert.Equal("27", target.ContainerFromIndex(items.Count - 4).DataContext);
  353. Assert.Equal("26", target.ContainerFromIndex(items.Count - 5).DataContext);
  354. }
  355. }
  356. [Fact]
  357. public void Clicking_Item_Should_Raise_BringIntoView_For_Correct_Control()
  358. {
  359. using (UnitTestApplication.Start(TestServices.StyledWindow))
  360. {
  361. // Issue #3934
  362. var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToArray();
  363. var target = new ListBox
  364. {
  365. Template = ListBoxTemplate(),
  366. ItemsSource = items,
  367. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 }),
  368. SelectionMode = SelectionMode.AlwaysSelected,
  369. };
  370. Prepare(target);
  371. Threading.Dispatcher.UIThread.RunJobs();
  372. // First an item that is not index 0 must be selected.
  373. _mouse.Click(target.Presenter.Panel.Children[1]);
  374. Threading.Dispatcher.UIThread.RunJobs();
  375. Assert.Equal(1, target.Selection.AnchorIndex);
  376. // We're going to be clicking on item 9.
  377. var item = (ListBoxItem)target.Presenter.Panel.Children[9];
  378. var raised = 0;
  379. // Make sure a RequestBringIntoView event is raised for item 9. It won't be handled
  380. // by the ScrollContentPresenter as the item is already visible, so we don't need
  381. // handledEventsToo: true. Issue #3934 failed here because item 0 was being scrolled
  382. // into view due to SelectionMode.AlwaysSelected.
  383. target.AddHandler(Control.RequestBringIntoViewEvent, (s, e) =>
  384. {
  385. Assert.Same(item, e.TargetObject);
  386. ++raised;
  387. });
  388. // Click item 9.
  389. _mouse.Click(item);
  390. Threading.Dispatcher.UIThread.RunJobs();
  391. Assert.Equal(1, raised);
  392. }
  393. }
  394. [Fact]
  395. public void Adding_And_Selecting_Item_With_AutoScrollToSelectedItem_Should_NotHide_FirstItem()
  396. {
  397. using (UnitTestApplication.Start(TestServices.StyledWindow))
  398. {
  399. var items = new AvaloniaList<string>();
  400. var wnd = new Window() { Width = 100, Height = 100, IsVisible = true };
  401. var target = new ListBox()
  402. {
  403. VerticalAlignment = VerticalAlignment.Top,
  404. AutoScrollToSelectedItem = true,
  405. Width = 50,
  406. ItemTemplate = new FuncDataTemplate<object>((c, _) => new Border() { Height = 10 }),
  407. ItemsSource = items,
  408. };
  409. wnd.Content = target;
  410. var lm = wnd.LayoutManager;
  411. lm.ExecuteInitialLayoutPass();
  412. var panel = target.Presenter.Panel;
  413. items.Add("Item 1");
  414. target.Selection.Select(0);
  415. lm.ExecuteLayoutPass();
  416. Assert.Equal(1, panel.Children.Count);
  417. items.Add("Item 2");
  418. target.Selection.Select(1);
  419. lm.ExecuteLayoutPass();
  420. Assert.Equal(2, panel.Children.Count);
  421. //make sure we have enough space to show all items
  422. Assert.True(panel.Bounds.Height >= panel.Children.Sum(c => c.Bounds.Height));
  423. //make sure we show items and they completelly visible, not only partially
  424. Assert.True(panel.Children[0].Bounds.Top >= 0 && panel.Children[0].Bounds.Bottom <= panel.Bounds.Height, "first item is not completelly visible!");
  425. Assert.True(panel.Children[1].Bounds.Top >= 0 && panel.Children[1].Bounds.Bottom <= panel.Bounds.Height, "second item is not completelly visible!");
  426. }
  427. }
  428. [Fact]
  429. public void Initial_Binding_Of_SelectedItems_Should_Not_Cause_Write_To_SelectedItems()
  430. {
  431. var target = new ListBox
  432. {
  433. [!ListBox.ItemsSourceProperty] = new Binding("Items"),
  434. [!ListBox.SelectedItemsProperty] = new Binding("SelectedItems"),
  435. };
  436. var viewModel = new
  437. {
  438. Items = new[] { "Foo", "Bar", "Baz " },
  439. SelectedItems = new ObservableCollection<string> { "Bar" },
  440. };
  441. var raised = 0;
  442. viewModel.SelectedItems.CollectionChanged += (s, e) => ++raised;
  443. target.DataContext = viewModel;
  444. Assert.Equal(0, raised);
  445. Assert.Equal(new[] { "Bar" }, viewModel.SelectedItems);
  446. Assert.Equal(new[] { "Bar" }, target.SelectedItems);
  447. Assert.Equal(new[] { "Bar" }, target.Selection.SelectedItems);
  448. }
  449. [Fact]
  450. public void Content_Can_Be_Bound_In_ItemContainerTheme()
  451. {
  452. using (UnitTestApplication.Start(TestServices.MockPlatformRenderInterface))
  453. {
  454. var items = new[] { new ItemViewModel("Foo"), new ItemViewModel("Bar") };
  455. var theme = new ControlTheme(typeof(ListBoxItem))
  456. {
  457. Setters =
  458. {
  459. new Setter(ListBoxItem.ContentProperty, new Binding("Caption")),
  460. }
  461. };
  462. var target = new ListBox
  463. {
  464. Template = ListBoxTemplate(),
  465. ItemsSource = items,
  466. ItemContainerTheme = theme,
  467. };
  468. Prepare(target);
  469. var containers = target.GetRealizedContainers().Cast<ListBoxItem>().ToList();
  470. Assert.Equal(2, containers.Count);
  471. Assert.Equal("Foo", containers[0].Content);
  472. Assert.Equal("Bar", containers[1].Content);
  473. }
  474. }
  475. private static FuncControlTemplate ListBoxTemplate()
  476. {
  477. return new FuncControlTemplate<ListBox>((parent, scope) =>
  478. new ScrollViewer
  479. {
  480. Name = "PART_ScrollViewer",
  481. Template = ScrollViewerTemplate(),
  482. Content = new ItemsPresenter
  483. {
  484. Name = "PART_ItemsPresenter",
  485. [~ItemsPresenter.ItemsPanelProperty] = parent.GetObservable(ItemsControl.ItemsPanelProperty).ToBinding(),
  486. }.RegisterInNameScope(scope)
  487. }.RegisterInNameScope(scope));
  488. }
  489. private static FuncControlTemplate ScrollViewerTemplate()
  490. {
  491. return new FuncControlTemplate<ScrollViewer>((parent, scope) =>
  492. new Panel
  493. {
  494. Children =
  495. {
  496. new ScrollContentPresenter
  497. {
  498. Name = "PART_ContentPresenter",
  499. }.RegisterInNameScope(scope),
  500. new ScrollBar
  501. {
  502. Name = "verticalScrollBar",
  503. Orientation = Orientation.Vertical,
  504. }
  505. }
  506. });
  507. }
  508. private static void Prepare(ListBox target)
  509. {
  510. target.Width = target.Height = 100;
  511. var root = new TestRoot(target);
  512. root.LayoutManager.ExecuteInitialLayoutPass();
  513. }
  514. private static void Layout(Control c)
  515. {
  516. ((ILayoutRoot)c.GetVisualRoot()).LayoutManager.ExecuteLayoutPass();
  517. }
  518. private class Item
  519. {
  520. public Item(string value)
  521. {
  522. Value = value;
  523. }
  524. public string Value { get; }
  525. }
  526. [Fact]
  527. public void SelectedItem_Validation()
  528. {
  529. var target = new ListBox
  530. {
  531. Template = ListBoxTemplate(),
  532. ItemsSource = new[] { "Foo" },
  533. ItemTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()),
  534. SelectionMode = SelectionMode.AlwaysSelected,
  535. };
  536. Prepare(target);
  537. var exception = new System.InvalidCastException("failed validation");
  538. var textObservable = new BehaviorSubject<BindingNotification>(new BindingNotification(exception, BindingErrorType.DataValidationError));
  539. target.Bind(ComboBox.SelectedItemProperty, textObservable);
  540. Assert.True(DataValidationErrors.GetHasErrors(target));
  541. Assert.True(DataValidationErrors.GetErrors(target).SequenceEqual(new[] { exception }));
  542. }
  543. [Fact]
  544. public void Handles_Resetting_Items()
  545. {
  546. var items = new ResettingCollection(100);
  547. var target = new ListBox
  548. {
  549. Template = ListBoxTemplate(),
  550. ItemsSource = items,
  551. ItemTemplate = new FuncDataTemplate<string>((_, __) => new Canvas { Height = 10 }),
  552. };
  553. Prepare(target);
  554. var realized = target.GetRealizedContainers()
  555. .Cast<ListBoxItem>()
  556. .Select(x => (string)x.DataContext)
  557. .ToList();
  558. Assert.Equal(Enumerable.Range(0, 10).Select(x => $"Item{x}"), realized);
  559. items.Reverse();
  560. Layout(target);
  561. realized = target.GetRealizedContainers()
  562. .Cast<ListBoxItem>()
  563. .Select(x => (string)x.DataContext)
  564. .ToList();
  565. Assert.Equal(Enumerable.Range(0, 10).Select(x => $"Item{99 - x}"), realized);
  566. }
  567. [Fact]
  568. public void Handles_Resetting_Items_With_Existing_Selection_And_AutoScrollToSelectedItem()
  569. {
  570. var items = new ResettingCollection(100);
  571. var target = new ListBox
  572. {
  573. Template = ListBoxTemplate(),
  574. ItemsSource = items,
  575. ItemTemplate = new FuncDataTemplate<string>((_, __) => new Canvas { Height = 10 }),
  576. AutoScrollToSelectedItem = true,
  577. SelectedIndex = 1,
  578. };
  579. Prepare(target);
  580. var realized = target.GetRealizedContainers()
  581. .Cast<ListBoxItem>()
  582. .Select(x => (string)x.DataContext)
  583. .ToList();
  584. Assert.Equal(Enumerable.Range(0, 10).Select(x => $"Item{x}"), realized);
  585. items.Reverse();
  586. Layout(target);
  587. Threading.Dispatcher.UIThread.RunJobs();
  588. realized = target.GetRealizedContainers()
  589. .Cast<ListBoxItem>()
  590. .Select(x => (string)x.DataContext)
  591. .ToList();
  592. // "Item1" should remain selected, and now be at the bottom of the viewport.
  593. Assert.Equal(Enumerable.Range(0, 10).Select(x => $"Item{10 - x}"), realized);
  594. }
  595. [Fact]
  596. public void Arrow_Keys_Should_Move_Selection_Vertical()
  597. {
  598. using var app = UnitTestApplication.Start(TestServices.RealFocus);
  599. var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToArray();
  600. var target = new ListBox
  601. {
  602. Template = ListBoxTemplate(),
  603. ItemsSource = items,
  604. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 }),
  605. SelectedIndex = 0,
  606. };
  607. Prepare(target);
  608. RaiseKeyEvent(target, Key.Down);
  609. Assert.Equal(1, target.SelectedIndex);
  610. RaiseKeyEvent(target, Key.Down);
  611. Assert.Equal(2, target.SelectedIndex);
  612. RaiseKeyEvent(target, Key.Up);
  613. Assert.Equal(1, target.SelectedIndex);
  614. }
  615. [Fact]
  616. public void Arrow_Keys_Should_Move_Selection_Horizontal()
  617. {
  618. using var app = UnitTestApplication.Start(TestServices.RealFocus);
  619. var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToArray();
  620. var target = new ListBox
  621. {
  622. Template = ListBoxTemplate(),
  623. ItemsSource = items,
  624. ItemsPanel = new FuncTemplate<Panel>(() => new VirtualizingStackPanel
  625. {
  626. Orientation = Orientation.Horizontal
  627. }),
  628. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 }),
  629. SelectedIndex = 0,
  630. };
  631. Prepare(target);
  632. RaiseKeyEvent(target, Key.Right);
  633. Assert.Equal(1, target.SelectedIndex);
  634. RaiseKeyEvent(target, Key.Right);
  635. Assert.Equal(2, target.SelectedIndex);
  636. RaiseKeyEvent(target, Key.Left);
  637. Assert.Equal(1, target.SelectedIndex);
  638. }
  639. [Fact]
  640. public void Arrow_Keys_Should_Focus_Selection()
  641. {
  642. using var app = UnitTestApplication.Start(TestServices.RealFocus);
  643. var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToArray();
  644. var target = new ListBox
  645. {
  646. Template = ListBoxTemplate(),
  647. ItemsSource = items,
  648. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 }),
  649. SelectedIndex = 0,
  650. };
  651. Prepare(target);
  652. RaiseKeyEvent(target, Key.Down);
  653. Assert.True(target.ContainerFromIndex(1).IsFocused);
  654. RaiseKeyEvent(target, Key.Down);
  655. Assert.True(target.ContainerFromIndex(2).IsFocused);
  656. RaiseKeyEvent(target, Key.Up);
  657. Assert.True(target.ContainerFromIndex(1).IsFocused);
  658. }
  659. [Fact]
  660. public void Down_Key_Selecting_From_No_Selection_And_No_Focus_Selects_From_Start()
  661. {
  662. using var app = UnitTestApplication.Start(TestServices.RealFocus);
  663. var target = new ListBox
  664. {
  665. Template = ListBoxTemplate(),
  666. ItemsSource = new[] { "Foo", "Bar", "Baz" },
  667. Width = 100,
  668. Height = 100,
  669. };
  670. Prepare(target);
  671. RaiseKeyEvent(target, Key.Down);
  672. Assert.Equal(0, target.SelectedIndex);
  673. }
  674. [Fact]
  675. public void Down_Key_Selecting_From_No_Selection_Selects_From_Focus()
  676. {
  677. using var app = UnitTestApplication.Start(TestServices.RealFocus);
  678. var target = new ListBox
  679. {
  680. Template = ListBoxTemplate(),
  681. ItemsSource = new[] { "Foo", "Bar", "Baz" },
  682. Width = 100,
  683. Height = 100,
  684. };
  685. Prepare(target);
  686. target.ContainerFromIndex(1)!.Focus();
  687. RaiseKeyEvent(target, Key.Down);
  688. Assert.Equal(2, target.SelectedIndex);
  689. }
  690. [Fact]
  691. public void Ctrl_Down_Key_Moves_Focus_But_Not_Selection()
  692. {
  693. using var app = UnitTestApplication.Start(TestServices.RealFocus);
  694. var target = new ListBox
  695. {
  696. Template = ListBoxTemplate(),
  697. ItemsSource = new[] { "Foo", "Bar", "Baz" },
  698. Width = 100,
  699. Height = 100,
  700. SelectedIndex = 0,
  701. };
  702. Prepare(target);
  703. target.ContainerFromIndex(0)!.Focus();
  704. RaiseKeyEvent(target, Key.Down, KeyModifiers.Control);
  705. Assert.Equal(0, target.SelectedIndex);
  706. Assert.True(target.ContainerFromIndex(1).IsFocused);
  707. }
  708. [Fact]
  709. public void Down_Key_Brings_Unrealized_Selection_Into_View()
  710. {
  711. using var app = UnitTestApplication.Start(TestServices.RealFocus);
  712. var items = Enumerable.Range(0, 100).Select(x => $"Item {x}").ToArray();
  713. var target = new ListBox
  714. {
  715. Template = ListBoxTemplate(),
  716. ItemsSource = items,
  717. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Width = 20, Height = 10 }),
  718. Width = 100,
  719. Height = 100,
  720. SelectedIndex = 0,
  721. };
  722. Prepare(target);
  723. target.ContainerFromIndex(0)!.Focus();
  724. target.Scroll.Offset = new Vector(0, 100);
  725. Layout(target);
  726. var panel = (VirtualizingStackPanel)target.ItemsPanelRoot;
  727. Assert.Equal(10, panel.FirstRealizedIndex);
  728. RaiseKeyEvent(target, Key.Down);
  729. Assert.Equal(1, target.SelectedIndex);
  730. Assert.True(target.ContainerFromIndex(1).IsFocused);
  731. Assert.Equal(new Vector(0, 10), target.Scroll.Offset);
  732. }
  733. [Fact]
  734. public void WrapSelection_Should_Wrap()
  735. {
  736. using (UnitTestApplication.Start(TestServices.RealFocus))
  737. {
  738. var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToArray();
  739. var target = new ListBox
  740. {
  741. Template = ListBoxTemplate(),
  742. ItemsSource = items,
  743. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 }),
  744. WrapSelection = true
  745. };
  746. Prepare(target);
  747. var lbItems = target.GetLogicalChildren().OfType<ListBoxItem>().ToArray();
  748. var first = lbItems.First();
  749. var beforeLast = lbItems[^2];
  750. var last = lbItems.Last();
  751. first.Focus();
  752. RaisePressedEvent(first, MouseButton.Left);
  753. Assert.Equal(true, first.IsSelected);
  754. RaiseKeyEvent(target, Key.Up);
  755. Assert.Equal(true, last.IsSelected);
  756. RaiseKeyEvent(target, Key.Up);
  757. Assert.Equal(true, beforeLast.IsSelected);
  758. RaiseKeyEvent(target, Key.Down);
  759. Assert.Equal(true, last.IsSelected);
  760. RaiseKeyEvent(target, Key.Down);
  761. Assert.Equal(true, first.IsSelected);
  762. target.WrapSelection = false;
  763. RaiseKeyEvent(target, Key.Up);
  764. Assert.Equal(true, first.IsSelected);
  765. }
  766. }
  767. [Fact]
  768. public void ContainerPrepared_Is_Raised_For_Each_Item_Container_On_Layout()
  769. {
  770. using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
  771. var target = new ListBox
  772. {
  773. Template = ListBoxTemplate(),
  774. Items = { "Foo", "Bar", "Baz" },
  775. };
  776. var result = new List<Control>();
  777. var index = 0;
  778. target.ContainerPrepared += (s, e) =>
  779. {
  780. Assert.Equal(index++, e.Index);
  781. result.Add(e.Container);
  782. };
  783. Prepare(target);
  784. Assert.Equal(3, result.Count);
  785. Assert.Equal(target.GetRealizedContainers(), result);
  786. }
  787. [Fact]
  788. public void ContainerPrepared_Is_Raised_For_Each_ItemsSource_Container_On_Layout()
  789. {
  790. using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
  791. var target = new ListBox
  792. {
  793. Template = ListBoxTemplate(),
  794. ItemsSource = new[] { "Foo", "Bar", "Baz" },
  795. };
  796. var result = new List<Control>();
  797. var index = 0;
  798. target.ContainerPrepared += (s, e) =>
  799. {
  800. Assert.Equal(index++, e.Index);
  801. result.Add(e.Container);
  802. };
  803. Prepare(target);
  804. Assert.Equal(3, result.Count);
  805. Assert.Equal(target.GetRealizedContainers(), result);
  806. }
  807. [Fact]
  808. public void ContainerPrepared_Is_Raised_For_Added_Item()
  809. {
  810. using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
  811. var data = new AvaloniaList<string> { "Foo", "Bar", "Baz" };
  812. var target = new ListBox
  813. {
  814. Template = ListBoxTemplate(),
  815. ItemsSource = data,
  816. };
  817. Prepare(target);
  818. var result = new List<Control>();
  819. target.ContainerPrepared += (s, e) =>
  820. {
  821. Assert.Equal(3, e.Index);
  822. result.Add(e.Container);
  823. };
  824. data.Add("Qux");
  825. Layout(target);
  826. Assert.Equal(1, result.Count);
  827. }
  828. [Fact]
  829. public void ContainerIndexChanged_Is_Raised_When_Item_Added()
  830. {
  831. using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
  832. var data = new AvaloniaList<string> { "Foo", "Bar", "Baz" };
  833. var target = new ListBox
  834. {
  835. Template = ListBoxTemplate(),
  836. ItemsSource = data,
  837. };
  838. Prepare(target);
  839. var result = new List<Control>();
  840. var index = 1;
  841. target.ContainerIndexChanged += (s, e) =>
  842. {
  843. Assert.Equal(index++, e.OldIndex);
  844. Assert.Equal(index, e.NewIndex);
  845. result.Add(e.Container);
  846. };
  847. data.Insert(1, "Qux");
  848. Layout(target);
  849. Assert.Equal(2, result.Count);
  850. Assert.Equal(target.GetRealizedContainers().Skip(2), result);
  851. }
  852. [Fact]
  853. public void ContainerClearing_Is_Raised_When_Item_Removed()
  854. {
  855. using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
  856. var data = new AvaloniaList<string> { "Foo", "Bar", "Baz" };
  857. var target = new ListBox
  858. {
  859. Template = ListBoxTemplate(),
  860. ItemsSource = data,
  861. };
  862. Prepare(target);
  863. var expected = target.ContainerFromIndex(1);
  864. var raised = 0;
  865. target.ContainerClearing += (s, e) =>
  866. {
  867. Assert.Same(expected, e.Container);
  868. ++raised;
  869. };
  870. data.RemoveAt(1);
  871. Layout(target);
  872. Assert.Equal(1, raised);
  873. }
  874. [Fact]
  875. public void Tab_Navigation_Should_Move_To_First_Item_When_No_Anchor_Element_Selected()
  876. {
  877. var services = TestServices.StyledWindow.With(
  878. keyboardDevice: () => new KeyboardDevice());
  879. using var app = UnitTestApplication.Start(services);
  880. var target = new ListBox
  881. {
  882. Template = ListBoxTemplate(),
  883. Items = { "Foo", "Bar", "Baz" },
  884. };
  885. var button = new Button
  886. {
  887. Content = "Button",
  888. [DockPanel.DockProperty] = Dock.Top,
  889. };
  890. var root = new TestRoot
  891. {
  892. Child = new DockPanel
  893. {
  894. Children =
  895. {
  896. button,
  897. target,
  898. }
  899. }
  900. };
  901. var navigation = new KeyboardNavigationHandler();
  902. navigation.SetOwner(root);
  903. root.LayoutManager.ExecuteInitialLayoutPass();
  904. button.Focus();
  905. RaiseKeyEvent(button, Key.Tab);
  906. var item = target.ContainerFromIndex(0);
  907. Assert.Same(item, root.FocusManager.GetFocusedElement());
  908. }
  909. [Fact]
  910. public void Tab_Navigation_Should_Move_To_Anchor_Element()
  911. {
  912. var services = TestServices.StyledWindow.With(
  913. keyboardDevice: () => new KeyboardDevice());
  914. using var app = UnitTestApplication.Start(services);
  915. var target = new ListBox
  916. {
  917. Template = ListBoxTemplate(),
  918. Items = { "Foo", "Bar", "Baz" },
  919. };
  920. var button = new Button
  921. {
  922. Content = "Button",
  923. [DockPanel.DockProperty] = Dock.Top,
  924. };
  925. var root = new TestRoot
  926. {
  927. Width = 1000,
  928. Height = 1000,
  929. Child = new DockPanel
  930. {
  931. Children =
  932. {
  933. button,
  934. target,
  935. }
  936. }
  937. };
  938. var navigation = new KeyboardNavigationHandler();
  939. navigation.SetOwner(root);
  940. root.LayoutManager.ExecuteInitialLayoutPass();
  941. button.Focus();
  942. target.Selection.AnchorIndex = 1;
  943. RaiseKeyEvent(button, Key.Tab);
  944. var item = target.ContainerFromIndex(1);
  945. Assert.Same(item, root.FocusManager.GetFocusedElement());
  946. RaiseKeyEvent(item, Key.Tab);
  947. Assert.Same(button, root.FocusManager.GetFocusedElement());
  948. target.Selection.AnchorIndex = 2;
  949. RaiseKeyEvent(button, Key.Tab);
  950. item = target.ContainerFromIndex(2);
  951. Assert.Same(item, root.FocusManager.GetFocusedElement());
  952. }
  953. [Fact]
  954. public void Reads_Only_Realized_Items_From_ItemsSource()
  955. {
  956. using var app = UnitTestApplication.Start(TestServices.MockPlatformRenderInterface);
  957. var data = new DataVirtualizingList();
  958. var target = new ListBox
  959. {
  960. Template = ListBoxTemplate(),
  961. ItemsSource = data,
  962. };
  963. Prepare(target);
  964. var panel = Assert.IsType<VirtualizingStackPanel>(target.ItemsPanelRoot);
  965. Assert.Equal(0, panel.FirstRealizedIndex);
  966. Assert.Equal(9, panel.LastRealizedIndex);
  967. Assert.Equal(
  968. Enumerable.Range(0, 10).Select(x => $"Item{x}"),
  969. data.GetRealizedItems());
  970. }
  971. [Fact]
  972. public void Should_Not_Handle_Space_When_TextBox_Inside_ListBoxItem()
  973. {
  974. using (UnitTestApplication.Start(TestServices.RealFocus))
  975. {
  976. var target = new TextBox
  977. {
  978. Focusable = true
  979. };
  980. var listbox = new ListBox()
  981. {
  982. Template = ListBoxTemplate(),
  983. Items =
  984. {
  985. new ListBoxItem()
  986. {
  987. Content = target,
  988. }
  989. }
  990. };
  991. var nKeyDown = 0;
  992. var root = new TestRoot()
  993. {
  994. Width = 1000,
  995. Height = 1000,
  996. Child = listbox,
  997. };
  998. root.KeyDown += (s, e) => nKeyDown++;
  999. listbox.ApplyTemplate();
  1000. root.LayoutManager.ExecuteInitialLayoutPass();
  1001. target.Focus();
  1002. RaiseKeyEvent(target, Key.Space, KeyModifiers.None);
  1003. Assert.Equal(1, nKeyDown);
  1004. }
  1005. }
  1006. [Fact]
  1007. public void ListBoxItem_Should_Not_Block_Tapped_Events()
  1008. {
  1009. // #13474
  1010. using (UnitTestApplication.Start(TestServices.StyledWindow))
  1011. {
  1012. Pointer _pointer = new Pointer(Pointer.GetNextFreeId(), PointerType.Touch, true);
  1013. ulong nextStamp = 1;
  1014. var items = Enumerable.Range(0, 10).Select(x => $"Item {x}").ToArray();
  1015. var target = new ListBox
  1016. {
  1017. Template = ListBoxTemplate(),
  1018. ItemsSource = items,
  1019. SelectionMode = SelectionMode.Toggle,
  1020. ItemTemplate = new FuncDataTemplate<string>((x, _) => new TextBlock { Height = 10 })
  1021. };
  1022. Prepare(target);
  1023. var lbItems = target.GetLogicalChildren().OfType<ListBoxItem>().ToArray();
  1024. var item = lbItems[0];
  1025. int tappedCount = 0;
  1026. target.Tapped += (s, e) =>
  1027. {
  1028. tappedCount++;
  1029. };
  1030. _mouse.Click(item);
  1031. Assert.Equal(1, tappedCount);
  1032. // Raise PointerPressed and PointerReleased events with the Left Button pressed. TouchTestHelper
  1033. // assumes no button pressed, which prevents it from generating Tapped events, or I would use that.
  1034. item.RaiseEvent(new PointerPressedEventArgs(item, _pointer, (Visual)item, default, nextStamp++,
  1035. new PointerPointProperties(RawInputModifiers.None, PointerUpdateKind.LeftButtonPressed), KeyModifiers.None));
  1036. item.RaiseEvent(new PointerReleasedEventArgs(item, _pointer, (Visual)item, default, nextStamp++,
  1037. PointerPointProperties.None, KeyModifiers.None, MouseButton.Left));
  1038. Assert.Equal(2, tappedCount);
  1039. }
  1040. }
  1041. private static void RaiseKeyEvent(Control target, Key key, KeyModifiers inputModifiers = 0)
  1042. {
  1043. target.RaiseEvent(new KeyEventArgs
  1044. {
  1045. RoutedEvent = InputElement.KeyDownEvent,
  1046. KeyModifiers = inputModifiers,
  1047. Key = key
  1048. });
  1049. }
  1050. private record ItemViewModel(string Caption);
  1051. private class ResettingCollection : List<string>, INotifyCollectionChanged
  1052. {
  1053. public ResettingCollection(int itemCount)
  1054. {
  1055. AddRange(Enumerable.Range(0, itemCount).Select(x => $"Item{x}"));
  1056. }
  1057. public new void Reverse()
  1058. {
  1059. base.Reverse();
  1060. CollectionChanged?.Invoke(
  1061. this,
  1062. new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  1063. }
  1064. public event NotifyCollectionChangedEventHandler CollectionChanged;
  1065. }
  1066. private class DataVirtualizingList : IList
  1067. {
  1068. private readonly List<string> _inner = new(Enumerable.Repeat<string>(null, 100));
  1069. public object this[int index]
  1070. {
  1071. get => _inner[index] = $"Item{index}";
  1072. set => throw new NotSupportedException();
  1073. }
  1074. public IEnumerable<string> GetRealizedItems() => _inner.Where(x => x is not null);
  1075. public bool IsFixedSize => true;
  1076. public bool IsReadOnly => true;
  1077. public int Count => _inner.Count;
  1078. public bool IsSynchronized => false;
  1079. public object SyncRoot => this;
  1080. public int Add(object value) => throw new NotSupportedException();
  1081. public void Clear() => throw new NotSupportedException();
  1082. public bool Contains(object value) => throw new NotImplementedException();
  1083. public void CopyTo(Array array, int index) => throw new NotImplementedException();
  1084. public IEnumerator GetEnumerator() => _inner.GetEnumerator();
  1085. public int IndexOf(object value) => throw new NotImplementedException();
  1086. public void Insert(int index, object value) => throw new NotSupportedException();
  1087. public void Remove(object value) => throw new NotSupportedException();
  1088. public void RemoveAt(int index) => throw new NotSupportedException();
  1089. }
  1090. }
  1091. }