ViewModelViewHostTest.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. FadeOutAnimation = null,
  30. FadeInAnimation = null
  31. };
  32. var root = new TestRoot
  33. {
  34. Child = host
  35. };
  36. Assert.NotNull(host.Content);
  37. Assert.Equal(typeof(TextBlock), host.Content.GetType());
  38. Assert.Equal(defaultContent, host.Content);
  39. var first = new FirstViewModel();
  40. host.ViewModel = first;
  41. Assert.NotNull(host.Content);
  42. Assert.Equal(typeof(FirstView), host.Content.GetType());
  43. Assert.Equal(first, ((FirstView)host.Content).DataContext);
  44. Assert.Equal(first, ((FirstView)host.Content).ViewModel);
  45. var second = new SecondViewModel();
  46. host.ViewModel = second;
  47. Assert.NotNull(host.Content);
  48. Assert.Equal(typeof(SecondView), host.Content.GetType());
  49. Assert.Equal(second, ((SecondView)host.Content).DataContext);
  50. Assert.Equal(second, ((SecondView)host.Content).ViewModel);
  51. host.ViewModel = null;
  52. Assert.NotNull(host.Content);
  53. Assert.Equal(typeof(TextBlock), host.Content.GetType());
  54. Assert.Equal(defaultContent, host.Content);
  55. host.ViewModel = first;
  56. Assert.NotNull(host.Content);
  57. Assert.Equal(typeof(FirstView), host.Content.GetType());
  58. Assert.Equal(first, ((FirstView)host.Content).DataContext);
  59. Assert.Equal(first, ((FirstView)host.Content).ViewModel);
  60. }
  61. }
  62. }