ListBoxTests.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright (c) The Perspex Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System.Linq;
  4. using Perspex.Controls.Presenters;
  5. using Perspex.Controls.Templates;
  6. using Perspex.LogicalTree;
  7. using Perspex.Styling;
  8. using Xunit;
  9. namespace Perspex.Controls.UnitTests
  10. {
  11. public class ListBoxTests
  12. {
  13. [Fact]
  14. public void LogicalChildren_Should_Be_Set()
  15. {
  16. var target = new ListBox
  17. {
  18. Template = new ControlTemplate(CreateListBoxTemplate),
  19. Items = new[] { "Foo", "Bar", "Baz " },
  20. };
  21. target.ApplyTemplate();
  22. Assert.Equal(3, target.GetLogicalChildren().Count());
  23. foreach (var child in target.GetLogicalChildren())
  24. {
  25. Assert.IsType<ListBoxItem>(child);
  26. }
  27. }
  28. [Fact]
  29. public void DataContexts_Should_Be_Correctly_Set()
  30. {
  31. var items = new object[]
  32. {
  33. "Foo",
  34. new Item("Bar"),
  35. new TextBlock { Text = "Baz" },
  36. new ListBoxItem { Content = "Qux" },
  37. };
  38. var target = new ListBox
  39. {
  40. Template = new ControlTemplate(CreateListBoxTemplate),
  41. DataContext = "Base",
  42. DataTemplates = new DataTemplates
  43. {
  44. new FuncDataTemplate<Item>(x => new Button { Content = x })
  45. },
  46. Items = items,
  47. };
  48. target.ApplyTemplate();
  49. var dataContexts = target.Presenter.Panel.Children
  50. .Cast<Control>()
  51. .Select(x => x.DataContext)
  52. .ToList();
  53. Assert.Equal(
  54. new object[] { items[0], items[1], "Base", "Base" },
  55. dataContexts);
  56. }
  57. private Control CreateListBoxTemplate(ITemplatedControl parent)
  58. {
  59. return new ScrollViewer
  60. {
  61. Template = new ControlTemplate(CreateScrollViewerTemplate),
  62. Content = new ItemsPresenter
  63. {
  64. Name = "itemsPresenter",
  65. [~ItemsPresenter.ItemsProperty] = parent.GetObservable(ItemsControl.ItemsProperty),
  66. }
  67. };
  68. }
  69. private Control CreateScrollViewerTemplate(ITemplatedControl parent)
  70. {
  71. return new ScrollContentPresenter
  72. {
  73. [~ContentPresenter.ContentProperty] = parent.GetObservable(ContentControl.ContentProperty),
  74. };
  75. }
  76. private class Item
  77. {
  78. public Item(string value)
  79. {
  80. Value = value;
  81. }
  82. public string Value { get; }
  83. }
  84. }
  85. }