DataBoundControl.cs 2.9 KB

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