Skip to content

Commit

Permalink
Weak Parent
Browse files Browse the repository at this point in the history
  • Loading branch information
PureWeen committed May 21, 2024
1 parent 7ad1b69 commit 34b7434
Showing 1 changed file with 52 additions and 6 deletions.
58 changes: 52 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,26 @@ 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
{
// Log an error because this should never happen
}

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

bool emitChange = Parent != value;
Expand All @@ -300,7 +316,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 +329,36 @@ 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
{
// Log an error because this should never happen
}

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 +374,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 34b7434

Please sign in to comment.