浏览代码

Merge pull request #724 from BDisp/added-removing-view-events

Fixes #723 Views now are notified when they are added or removing.
Charlie Kindel 5 年之前
父节点
当前提交
0f64ac6ea9
共有 2 个文件被更改,包括 51 次插入0 次删除
  1. 30 0
      Terminal.Gui/Core/View.cs
  2. 21 0
      UnitTests/ViewTests.cs

+ 30 - 0
Terminal.Gui/Core/View.cs

@@ -124,6 +124,16 @@ namespace Terminal.Gui {
 
 		TextFormatter viewText;
 
+		/// <summary>
+		/// Event fired when a subview is being added to this view.
+		/// </summary>
+		public Action<View> Added;
+
+		/// <summary>
+		/// Event fired when a subview is being removed from this view.
+		/// </summary>
+		public Action<View> Removed;
+
 		/// <summary>
 		/// Event fired when the view gets focus.
 		/// </summary>
@@ -552,6 +562,7 @@ namespace Terminal.Gui {
 				subviews = new List<View> ();
 			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; }
 		}
 
+		/// <summary>
+		/// Method invoked  when a subview is being added to this view.
+		/// </summary>
+		/// <param name="view">The subview being added.</param>
+		public virtual void OnAdded (View view)
+		{
+			view.Added?.Invoke (this);
+		}
+
+		/// <summary>
+		/// Method invoked when a subview is being removed from this view.
+		/// </summary>
+		/// <param name="view">The subview being removed.</param>
+		public virtual void OnRemoved (View view)
+		{
+			view.Removed?.Invoke (this);
+		}
+
 		/// <inheritdoc/>
 		public override bool OnEnter (View view)
 		{

+ 21 - 0
UnitTests/ViewTests.cs

@@ -135,5 +135,26 @@ namespace Terminal.Gui {
 			sub2.Width = Dim.Width (sub2);
 			Assert.Throws<InvalidOperationException> (() => 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);
+		}
 	}
 }