ViewLocator.cs 717 B

123456789101112131415161718192021222324252627282930313233343536
  1. using Avalonia.Controls;
  2. using Avalonia.Controls.Templates;
  3. using HelloItQuantum.ViewModels;
  4. using System;
  5. namespace HelloItQuantum
  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 = Activator.CreateInstance(type) as Control;
  18. if (control != null)
  19. {
  20. control.DataContext = data;
  21. return control;
  22. }
  23. }
  24. return new TextBlock { Text = "Not Found: " + name };
  25. }
  26. public bool Match(object? data)
  27. {
  28. return data is ViewModelBase;
  29. }
  30. }
  31. }