ViewLocator.cs 845 B

12345678910111213141516171819202122232425262728293031323334
  1. using Avalonia.Controls;
  2. using Avalonia.Controls.Templates;
  3. using EntranseTesting.ViewModels;
  4. using System;
  5. namespace EntranseTesting
  6. {
  7. public class ViewLocator : IDataTemplate
  8. {
  9. public Control? Build(object? data)
  10. {
  11. if (data is null)
  12. return null;
  13. var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);
  14. var type = Type.GetType(name);
  15. if (type != null)
  16. {
  17. var control = (Control)Activator.CreateInstance(type)!;
  18. control.DataContext = data;
  19. return control;
  20. }
  21. return new TextBlock { Text = "Not Found: " + name };
  22. }
  23. public bool Match(object? data)
  24. {
  25. return data is ViewModelBase;
  26. }
  27. }
  28. }