ViewModelViewHostTest.cs 2.6 KB

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