PropertyGrid.axaml.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Interactivity;
  4. using Avalonia.Markup.Xaml;
  5. using System.ComponentModel;
  6. // ReSharper disable once CheckNamespace
  7. namespace SukiUI.Controls
  8. {
  9. public partial class PropertyGrid : UserControl
  10. {
  11. static PropertyGrid()
  12. {
  13. ItemProperty.Changed.AddClassHandler<PropertyGrid>((_, args) => OnItemChanged(args));
  14. }
  15. public PropertyGrid()
  16. {
  17. InitializeComponent();
  18. }
  19. private void InitializeComponent()
  20. {
  21. AvaloniaXamlLoader.Load(this);
  22. }
  23. public static readonly StyledProperty<INotifyPropertyChanged?> ItemProperty = AvaloniaProperty.Register<PropertyGrid, INotifyPropertyChanged?>(nameof(Item), defaultValue: null);
  24. public INotifyPropertyChanged? Item
  25. {
  26. get { return GetValue(ItemProperty); }
  27. set { SetValue(ItemProperty, value); }
  28. }
  29. public static readonly StyledProperty<InstanceViewModel?> InstanceProperty = AvaloniaProperty.Register<PropertyGrid, InstanceViewModel?>(nameof(Instance), defaultValue: null);
  30. public InstanceViewModel? Instance
  31. {
  32. get { return GetValue(InstanceProperty); }
  33. set { SetValue(InstanceProperty, value); }
  34. }
  35. private static void OnItemChanged( AvaloniaPropertyChangedEventArgs e)
  36. {
  37. if (e.Sender is PropertyGrid propertyGrid)
  38. {
  39. propertyGrid.OnItemChanged(e.NewValue);
  40. }
  41. }
  42. private void OnItemChanged(object? newValue)
  43. {
  44. SetItem(newValue as INotifyPropertyChanged);
  45. }
  46. protected virtual void SetItem(INotifyPropertyChanged? item)
  47. {
  48. if (item is null)
  49. {
  50. return;
  51. }
  52. Instance = new InstanceViewModel(item);
  53. }
  54. protected override void OnUnloaded(RoutedEventArgs e)
  55. {
  56. base.OnUnloaded(e);
  57. Instance?.Dispose();
  58. }
  59. }
  60. }