Type2ViewConverter.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using Avalonia.Controls;
  2. using Avalonia.Data.Converters;
  3. using System;
  4. using System.Collections.Concurrent;
  5. using System.Collections.Generic;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace ShakerApp.Convert
  11. {
  12. public class Type2ViewConverter : IValueConverter
  13. {
  14. ConcurrentDictionary<RuntimeTypeHandle, Control> Views = new ConcurrentDictionary<RuntimeTypeHandle,Control>();
  15. public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
  16. {
  17. if (value is Type type)
  18. {
  19. if (parameter != null) return (Control)Activator.CreateInstance(type)!;
  20. else
  21. {
  22. if (Views.TryGetValue(type.TypeHandle, out var view)) return view;
  23. else
  24. {
  25. view = (Control)Activator.CreateInstance(type)!;
  26. Views[type.TypeHandle] = view;
  27. return view;
  28. }
  29. }
  30. }
  31. if(value is IList<Type> types)
  32. {
  33. if (parameter != null) return types.Where(x => x != null).Select(x => Activator.CreateInstance(x));
  34. else
  35. {
  36. return types.Where(x => x != null)
  37. .Select(x =>
  38. {
  39. if (Views.TryGetValue(x.TypeHandle, out var view)) return view;
  40. else
  41. {
  42. view = (Control)Activator.CreateInstance(x)!;
  43. Views[x.TypeHandle] = view;
  44. return view;
  45. }
  46. });
  47. }
  48. }
  49. return null;
  50. }
  51. public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
  52. {
  53. throw new NotImplementedException();
  54. }
  55. }
  56. }