Type2ViewConverter.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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))
  23. {
  24. if(view.Parent is ContentControl window)
  25. {
  26. window.Content = null;
  27. }
  28. return view;
  29. }
  30. else
  31. {
  32. view = (Control)Activator.CreateInstance(type)!;
  33. Views[type.TypeHandle] = view;
  34. return view;
  35. }
  36. }
  37. }
  38. if(value is IList<Type> types)
  39. {
  40. if (parameter != null) return types.Where(x => x != null).Select(x => Activator.CreateInstance(x));
  41. else
  42. {
  43. return types.Where(x => x != null)
  44. .Select(x =>
  45. {
  46. if (Views.TryGetValue(x.TypeHandle, out var view)) return view;
  47. else
  48. {
  49. view = (Control)Activator.CreateInstance(x)!;
  50. Views[x.TypeHandle] = view;
  51. return view;
  52. }
  53. });
  54. }
  55. }
  56. return null;
  57. }
  58. public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
  59. {
  60. throw new NotImplementedException();
  61. }
  62. }
  63. }