DataTemplateTests.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 Avalonia.Controls;
  4. using Avalonia.Controls.Presenters;
  5. using Avalonia.UnitTests;
  6. using Xunit;
  7. namespace Avalonia.Markup.Xaml.UnitTests.Xaml
  8. {
  9. public class DataTemplateTests
  10. {
  11. [Fact]
  12. public void DataTemplate_Can_Contain_Name()
  13. {
  14. using (UnitTestApplication.Start(TestServices.StyledWindow))
  15. {
  16. var xaml = @"
  17. <Window xmlns='https://github.com/avaloniaui'
  18. xmlns:sys='clr-namespace:System;assembly=mscorlib'
  19. xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
  20. <Window.DataTemplates>
  21. <DataTemplate DataType='{x:Type sys:String}'>
  22. <Canvas Name='foo'/>
  23. </DataTemplate>
  24. </Window.DataTemplates>
  25. <ContentControl Name='target' Content='Foo'/>
  26. </Window>";
  27. var loader = new AvaloniaXamlLoader();
  28. var window = (Window)loader.Load(xaml);
  29. var target = window.FindControl<ContentControl>("target");
  30. window.ApplyTemplate();
  31. target.ApplyTemplate();
  32. ((ContentPresenter)target.Presenter).UpdateChild();
  33. Assert.IsType<Canvas>(target.Presenter.Child);
  34. }
  35. }
  36. [Fact]
  37. public void Can_Set_DataContext_In_DataTemplate()
  38. {
  39. using (UnitTestApplication.Start(TestServices.StyledWindow))
  40. {
  41. var xaml = @"
  42. <Window xmlns='https://github.com/avaloniaui' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
  43. xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests;assembly=Avalonia.Markup.Xaml.UnitTests'>
  44. <Window.DataTemplates>
  45. <DataTemplate DataType='{x:Type local:TestViewModel}'>
  46. <Canvas Name='foo' DataContext='{Binding Child}'/>
  47. </DataTemplate>
  48. </Window.DataTemplates>
  49. <ContentControl Name='target' Content='{Binding Child}'/>
  50. </Window>";
  51. var loader = new AvaloniaXamlLoader();
  52. var window = (Window)loader.Load(xaml);
  53. var target = window.FindControl<ContentControl>("target");
  54. var viewModel = new TestViewModel
  55. {
  56. String = "Root",
  57. Child = new TestViewModel
  58. {
  59. String = "Child",
  60. Child = new TestViewModel
  61. {
  62. String = "Grandchild",
  63. }
  64. },
  65. };
  66. window.DataContext = viewModel;
  67. window.ApplyTemplate();
  68. target.ApplyTemplate();
  69. ((ContentPresenter)target.Presenter).UpdateChild();
  70. var canvas = (Canvas)target.Presenter.Child;
  71. Assert.Same(viewModel, target.DataContext);
  72. Assert.Same(viewModel.Child, target.Presenter.DataContext);
  73. Assert.Same(viewModel.Child.Child, canvas.DataContext);
  74. }
  75. }
  76. }
  77. }