//... static LayoutGroupControl GetParent(this ILayoutControl input, LayoutGroupControl parent = null) { if (parent == null) { if (ReferenceEquals(input.Root.Child, input)) { return(null); } if (input.Root.Child is LayoutGroupControl i) { return(input.GetParent(i)); } } foreach (var i in parent.Children) { if (ReferenceEquals(i, input)) { return(parent); } if (i is LayoutGroupControl j) { var result = input.GetParent(j); if (result != null) { return(result); } } } return(null); }
//... public static void Delete(this ILayoutControl input) { var parent = input.GetParent(); if (parent == null) { Unsubscribe(input); input.Root.Child = null; return; } var index = input.GetIndex(); if (index == -1) { throw new IndexOutOfRangeException(); } Unsubscribe(input); parent.Children.RemoveAt(index); //Remove the column or row definition if (parent.Orientation == Orientation.Horizontal) { parent.ColumnDefinitions.RemoveAt(index); } if (parent.Orientation == Orientation.Vertical) { parent.RowDefinitions.RemoveAt(index); } if (parent.Children.Count > 0) { if (index >= parent.Children.Count) { index = parent.Children.Count - 1; } //Remove the grid splitter if (index < parent.Children.Count) { if (parent.Children[index] is GridSplitter) { parent.Children.RemoveAt(index); //Remove the column or row definition again if (parent.Orientation == Orientation.Horizontal) { parent.ColumnDefinitions.RemoveAt(index); } if (parent.Orientation == Orientation.Vertical) { parent.RowDefinitions.RemoveAt(index); } } } } //Reassign all column or row values for (var i = 0; i < parent.Children.Count; i++) { if (parent.Orientation == Orientation.Horizontal) { Grid.SetColumn(parent.Children[i], i); } if (parent.Orientation == Orientation.Vertical) { Grid.SetRow(parent.Children[i], i); } } //Remove the parent from it's own parent to avoid empty LayoutGroupControls if (parent.Children.Count == 0) { parent.Delete(); } }
//... public static int GetIndex(this ILayoutControl input) => input.GetParent()?.Children.IndexOf(input as UIElement) ?? -1;
public static LayoutGroupControl GetParent(this ILayoutControl input) => input.GetParent(null);