ViewModelViewHostTest.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.UnitTests;
  5. using ReactiveUI;
  6. using Splat;
  7. using Xunit;
  8. namespace Avalonia.ReactiveUI.UnitTests
  9. {
  10. public class ViewModelViewHostTest
  11. {
  12. public class FirstViewModel { }
  13. public class FirstView : ReactiveUserControl<FirstViewModel> { }
  14. public class SecondViewModel : ReactiveObject { }
  15. public class SecondView : ReactiveUserControl<SecondViewModel> { }
  16. public ViewModelViewHostTest()
  17. {
  18. Locator.CurrentMutable.RegisterConstant(new AvaloniaActivationForViewFetcher(), typeof(IActivationForViewFetcher));
  19. Locator.CurrentMutable.Register(() => new FirstView(), typeof(IViewFor<FirstViewModel>));
  20. Locator.CurrentMutable.Register(() => new SecondView(), typeof(IViewFor<SecondViewModel>));
  21. }
  22. [Fact]
  23. public void ViewModelViewHost_View_Should_Stay_In_Sync_With_ViewModel()
  24. {
  25. var defaultContent = new TextBlock();
  26. var host = new ViewModelViewHost
  27. {
  28. DefaultContent = defaultContent,
  29. PageTransition = null
  30. };
  31. var root = new TestRoot
  32. {
  33. Child = host
  34. };
  35. Assert.NotNull(host.Content);
  36. Assert.Equal(typeof(TextBlock), host.Content.GetType());
  37. Assert.Equal(defaultContent, host.Content);
  38. var first = new FirstViewModel();
  39. host.ViewModel = first;
  40. Assert.NotNull(host.Content);
  41. Assert.Equal(typeof(FirstView), host.Content.GetType());
  42. Assert.Equal(first, ((FirstView)host.Content).DataContext);
  43. Assert.Equal(first, ((FirstView)host.Content).ViewModel);
  44. var second = new SecondViewModel();
  45. host.ViewModel = second;
  46. Assert.NotNull(host.Content);
  47. Assert.Equal(typeof(SecondView), host.Content.GetType());
  48. Assert.Equal(second, ((SecondView)host.Content).DataContext);
  49. Assert.Equal(second, ((SecondView)host.Content).ViewModel);
  50. host.ViewModel = null;
  51. Assert.NotNull(host.Content);
  52. Assert.Equal(typeof(TextBlock), host.Content.GetType());
  53. Assert.Equal(defaultContent, host.Content);
  54. host.ViewModel = first;
  55. Assert.NotNull(host.Content);
  56. Assert.Equal(typeof(FirstView), host.Content.GetType());
  57. Assert.Equal(first, ((FirstView)host.Content).DataContext);
  58. Assert.Equal(first, ((FirstView)host.Content).ViewModel);
  59. }
  60. }
  61. }