Skip to content

Commit

Permalink
fix: hosted native components were attached at an incorrect time
Browse files Browse the repository at this point in the history
  • Loading branch information
ramezgerges committed Jun 20, 2024
1 parent 5add726 commit c94b4a7
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
27 changes: 25 additions & 2 deletions src/Uno.UI/UI/Xaml/Controls/ContentPresenter/ContentPresenter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -757,7 +757,7 @@ protected virtual void OnContentChanged(object oldValue, object newValue)

TrySetDataContextFromContent(newValue);

if (IsLoaded)
if (IsActiveInVisualTree)
{
TryRegisterNativeElement(oldValue, newValue);
}
Expand Down Expand Up @@ -941,6 +941,27 @@ internal override void Enter(EnterParams @params, int depth)
#if !UNO_HAS_BORDER_VISUAL
UpdateBorder();
#endif

// We do this in Enter not Loaded since Loaded is a lot more tricky
// (e.g. you can have Unloaded without Loaded, you can have multiple loaded events without unloaded in between, etc.)
if (!IsNativeHost)
{
TryRegisterNativeElement(null, Content);
}
if (IsNativeHost)
{
AttachNativeElement();
}
}

internal override void Leave(LeaveParams @params)
{
base.Leave(@params);

if (IsNativeHost)
{
DetachNativeElement(Content);
}
}
#endif

Expand Down Expand Up @@ -971,7 +992,6 @@ private protected override void OnLoaded()

#if !UNO_HAS_ENHANCED_LIFECYCLE
UpdateBorder();
#endif

if (!IsNativeHost)
{
Expand All @@ -981,16 +1001,19 @@ private protected override void OnLoaded()
{
AttachNativeElement();
}
#endif
}

private protected override void OnUnloaded()
{
base.OnUnloaded();

#if !UNO_HAS_ENHANCED_LIFECYCLE
if (IsNativeHost)
{
DetachNativeElement(Content);
}
#endif
}

private bool ResetDataContextOnFirstLoad()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ partial void InitializePlatform()

partial void TryRegisterNativeElement(object oldValue, object newValue)
{
if (IsNativeHost && IsLoaded)
if (IsNativeHost && IsActiveInVisualTree)
{
DetachNativeElement(oldValue);
}
Expand All @@ -59,9 +59,9 @@ partial void TryRegisterNativeElement(object oldValue, object newValue)
throw new InvalidOperationException("ContentTemplateSelector cannot be set when the Content is a native element");
}

if (IsLoaded)
if (IsActiveInVisualTree)
{
//If loaded, attach immediately. If not, don't attach since OnLoaded will attach later.
//If in visual tree, attach immediately. If not, don't attach since Enter will attach later.
AttachNativeElement();
}
}
Expand Down

0 comments on commit c94b4a7

Please sign in to comment.