DataBoundControl.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using SRF.Helpers;
  3. using UnityEngine;
  4. namespace SRDebugger.UI.Controls
  5. {
  6. public abstract class DataBoundControl : OptionsControlBase
  7. {
  8. public SRF.Helpers.PropertyReference Property
  9. {
  10. get
  11. {
  12. return this._prop;
  13. }
  14. }
  15. public bool IsReadOnly
  16. {
  17. get
  18. {
  19. return this._isReadOnly;
  20. }
  21. }
  22. public string PropertyName { get; private set; }
  23. public void Bind(string propertyName, SRF.Helpers.PropertyReference prop)
  24. {
  25. this.PropertyName = propertyName;
  26. this._prop = prop;
  27. this._isReadOnly = !prop.CanWrite;
  28. this.OnBind(propertyName, prop.PropertyType);
  29. this.Refresh();
  30. }
  31. protected void UpdateValue(object newValue)
  32. {
  33. if (newValue == this._prevValue)
  34. {
  35. return;
  36. }
  37. if (this.IsReadOnly)
  38. {
  39. return;
  40. }
  41. this._prop.SetValue(newValue);
  42. this._prevValue = newValue;
  43. }
  44. public override void Refresh()
  45. {
  46. if (this._prop == null)
  47. {
  48. return;
  49. }
  50. object value = this._prop.GetValue();
  51. if (value != this._prevValue)
  52. {
  53. try
  54. {
  55. this.OnValueUpdated(value);
  56. }
  57. catch (Exception exception)
  58. {
  59. UnityEngine.Debug.LogError("[SROptions] Error refreshing binding.");
  60. UnityEngine.Debug.LogException(exception);
  61. }
  62. }
  63. this._prevValue = value;
  64. }
  65. protected virtual void OnBind(string propertyName, Type t)
  66. {
  67. }
  68. protected abstract void OnValueUpdated(object newValue);
  69. public abstract bool CanBind(Type type, bool isReadOnly);
  70. protected override void Start()
  71. {
  72. base.Start();
  73. this.Refresh();
  74. this._hasStarted = true;
  75. }
  76. protected override void OnEnable()
  77. {
  78. base.OnEnable();
  79. if (this._hasStarted)
  80. {
  81. this.Refresh();
  82. }
  83. }
  84. private bool _hasStarted;
  85. private bool _isReadOnly;
  86. private object _prevValue;
  87. private SRF.Helpers.PropertyReference _prop;
  88. }
  89. }