ViewLocator.cs 836 B

1234567891011121314151617181920212223
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.Templates;
  4. using System.Linq;
  5. namespace SukiUI.Helpers;
  6. internal static class ViewLocator
  7. {
  8. private static IDataTemplate? _locator;
  9. /// <summary>
  10. /// Tries to build a suitable control using an appropriate DataTemplate provided by the App.
  11. /// </summary>
  12. /// <param name="data"></param>
  13. /// <returns>A valid control provided by a suitable ViewLocator if available, otherwise returns an error TextBlock.</returns>
  14. internal static Control TryBuild(object? data)
  15. {
  16. if (data is string s) return new TextBlock() { Text = s };
  17. _locator ??= Application.Current?.DataTemplates.FirstOrDefault();
  18. return _locator?.Build(data) ?? new TextBlock() { Text = $"Unable to find suitable view for {data?.GetType().Name}" };
  19. }
  20. }