Skip to content

Commit

Permalink
Weak Parent (#22561)
Browse files Browse the repository at this point in the history
* Weak Parent

* - add logging
  • Loading branch information
PureWeen authored May 27, 2024
1 parent 738519d commit 10e3fc4
Showing 1 changed file with 58 additions and 6 deletions.
64 changes: 58 additions & 6 deletions src/Controls/src/Core/Element/Element.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public abstract partial class Element : BindableObject, IElementDefinition, INam

Guid? _id;

Element _parentOverride;
WeakReference<Element> _parentOverride;

string _styleId;

Expand Down Expand Up @@ -282,10 +282,29 @@ internal bool RemoveLogicalChild(Element element, int index)

internal Element ParentOverride
{
get { return _parentOverride; }
get
{
if (_parentOverride is null)
{
return null;
}
if (_parentOverride.TryGetTarget(out var parent))
{
return parent;
}
else
{
Application.Current?
.FindMauiContext()?
.CreateLogger<Element>()?
.LogWarning($"The ParentOverride on {this} has been Garbage Collected. This should never happen. Please log a bug: https://github.com/dotnet/maui");
}

return null;
}
set
{
if (_parentOverride == value)
if (ParentOverride == value)
return;

bool emitChange = Parent != value;
Expand All @@ -300,7 +319,10 @@ internal Element ParentOverride
OnParentChangingCore(Parent, RealParent);
}

_parentOverride = value;
if (value == null)
_parentOverride = null;
else
_parentOverride = new WeakReference<Element>(value);

if (emitChange)
{
Expand All @@ -310,9 +332,39 @@ internal Element ParentOverride
}
}

WeakReference<Element> _realParent;
/// <summary>For internal use by .NET MAUI.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public Element RealParent { get; private set; }
public Element RealParent
{
get
{
if (_realParent is null)
{
return null;
}
if (_realParent.TryGetTarget(out var parent))
{
return parent;
}
else
{
Application.Current?
.FindMauiContext()?
.CreateLogger<Element>()?
.LogWarning($"The RealParent on {this} has been Garbage Collected. This should never happen. Please log a bug: https://github.com/dotnet/maui");
}

return null;
}
private set
{
if (value is null)
_realParent = null;
else
_realParent = new WeakReference<Element>(value);
}
}

Dictionary<BindableProperty, (string, SetterSpecificity)> DynamicResources => _dynamicResources ?? (_dynamicResources = new Dictionary<BindableProperty, (string, SetterSpecificity)>());

Expand All @@ -328,7 +380,7 @@ void IElementDefinition.AddResourcesChangedListener(Action<object, ResourcesChan
/// <remarks>Most application authors will not need to set the parent element by hand.</remarks>
public Element Parent
{
get { return _parentOverride ?? RealParent; }
get { return ParentOverride ?? RealParent; }
set => SetParent(value);
}

Expand Down

0 comments on commit 10e3fc4

Please sign in to comment.