Skip to content

Commit

Permalink
Optimize GetChildOfType<T> Method
Browse files Browse the repository at this point in the history
  • Loading branch information
MakesYT committed Jan 29, 2024
1 parent d002e07 commit a77bcc6
Showing 1 changed file with 26 additions and 11 deletions.
37 changes: 26 additions & 11 deletions NodifyM.Avalonia/Helpers/DependencyObjectExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,27 +33,42 @@ internal static class DependencyObjectExtensions


}
public static T? GetChildOfType<T>(this Control control,string? name=null)
public static T? GetChildOfType<T>(this Control control, string? name = null)
where T : Control
{
if ((name ==null||control.Name == name)&& control is T control1)
return control1;
var stack = new Stack<Control>();
stack.Push(control);

foreach (var child in control.GetVisualChildren())
while (stack.Count > 0)
{
var foundChild = child as Control;
if (foundChild != null && (name==null||foundChild.Name == name)&& foundChild is T child1)
return child1;
else
var currentControl = stack.Pop();

if (string.IsNullOrEmpty(name) && currentControl is T targetControl)
{
return targetControl;
}

foreach (var child in currentControl.GetVisualChildren())
{
var result = ((foundChild).GetChildOfType<T>(name));
if (result != null)
return (T)result;
var childControl = child as Control;
if (childControl != null)
{
if (string.IsNullOrEmpty(name) || childControl.Name == name)
{
if (childControl is T targetChild)
{
return targetChild;
}
}

stack.Push(childControl);
}
}
}

return null;
}

public static T? GetVisualAt<T>(this Control control,Point anchor)
where T : Control
{
Expand Down

0 comments on commit a77bcc6

Please sign in to comment.