diff --git a/Terminal.Gui/Core/View.cs b/Terminal.Gui/Core/View.cs index b7ec0c0b6..e4c620680 100644 --- a/Terminal.Gui/Core/View.cs +++ b/Terminal.Gui/Core/View.cs @@ -124,6 +124,16 @@ namespace Terminal.Gui { TextFormatter viewText; + /// + /// Event fired when a subview is being added to this view. + /// + public Action Added; + + /// + /// Event fired when a subview is being removed from this view. + /// + public Action Removed; + /// /// Event fired when the view gets focus. /// @@ -552,6 +562,7 @@ namespace Terminal.Gui { subviews = new List (); subviews.Add (view); view.container = this; + OnAdded (view); if (view.CanFocus) CanFocus = true; SetNeedsLayout (); @@ -601,6 +612,7 @@ namespace Terminal.Gui { var touched = view.Frame; subviews.Remove (view); view.container = null; + OnRemoved (view); if (subviews.Count < 1) this.CanFocus = false; @@ -943,6 +955,24 @@ namespace Terminal.Gui { public View View { get; set; } } + /// + /// Method invoked when a subview is being added to this view. + /// + /// The subview being added. + public virtual void OnAdded (View view) + { + view.Added?.Invoke (this); + } + + /// + /// Method invoked when a subview is being removed from this view. + /// + /// The subview being removed. + public virtual void OnRemoved (View view) + { + view.Removed?.Invoke (this); + } + /// public override bool OnEnter (View view) { diff --git a/UnitTests/ViewTests.cs b/UnitTests/ViewTests.cs index 4904ff684..353335915 100644 --- a/UnitTests/ViewTests.cs +++ b/UnitTests/ViewTests.cs @@ -135,5 +135,26 @@ namespace Terminal.Gui { sub2.Width = Dim.Width (sub2); Assert.Throws (() => root.LayoutSubviews ()); } + + [Fact] + public void Added_Removing () + { + var v = new View (new Rect (0, 0, 10, 24)); + var t = new View (); + + v.Added += (View e) => { + Assert.True (v.SuperView == e); + }; + + v.Removed += (View e) => { + Assert.True (v.SuperView == null); + }; + + t.Add (v); + Assert.True (t.Subviews.Count == 1); + + t.Remove (v); + Assert.True (t.Subviews.Count == 0); + } } }