Browse Source

Fix System.InvalidCastException in PageNavigationHost (#21144)

* Fix invalid cast exception in PageNavigationHost

* Added tests

---------

Co-authored-by: Javier Suárez Ruiz <javiersuarezruiz@hotmail.com>
pull/21152/head
Emmanuel Hansen 2 months ago
committed by GitHub
parent
commit
7953595956
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 8
      src/Avalonia.Controls/Page/PageNavigationHost.cs
  2. 33
      tests/Avalonia.Controls.UnitTests/PageNavigationHostTests.cs

8
src/Avalonia.Controls/Page/PageNavigationHost.cs

@ -114,8 +114,8 @@ namespace Avalonia.Controls
if (change.Property == PageProperty)
{
var oldPage = change.GetOldValue<Page?>();
var newPage = change.GetNewValue<Page?>();
var oldPage = change.OldValue as Page;
var newPage = change.NewValue as Page;
SetCurrentValue(ContentProperty, newPage);
@ -132,10 +132,10 @@ namespace Avalonia.Controls
if (e.Property != ContentPresenter.ChildProperty)
return;
if (e.GetOldValue<object?>() is Page oldPage)
if (e.OldValue is Page oldPage)
oldPage.SafeAreaPadding = default;
if (e.GetNewValue<object?>() is Page newPage && _insetManager != null)
if (e.NewValue is Page newPage && _insetManager != null)
newPage.SafeAreaPadding = _insetManager.SafeAreaPadding;
}

33
tests/Avalonia.Controls.UnitTests/PageNavigationHostTests.cs

@ -129,5 +129,38 @@ public class PageNavigationHostTests
Assert.Equal("NavigatedFrom", order[0]);
Assert.Equal("NavigatedTo", order[1]);
}
[Fact]
public void InitialLayout_WithExistingPage_DoesNotThrow_WhenContentPresenterChildIsAssigned()
{
var page = new ContentPage { Header = "Home" };
var host = new PageNavigationHost { Page = page };
var root = new TestRoot { Child = host };
var exception = Record.Exception(() => root.LayoutManager.ExecuteInitialLayoutPass());
Assert.Null(exception);
Assert.NotNull(host.Presenter);
Assert.Same(page, host.Presenter!.Child);
}
[Fact]
public void ReplacingPage_ResetsOldPresenterChildSafeAreaPadding()
{
var first = new ContentPage { Header = "First" };
var second = new ContentPage { Header = "Second" };
var host = new PageNavigationHost { Page = first };
var root = new TestRoot { Child = host };
root.LayoutManager.ExecuteInitialLayoutPass();
first.SafeAreaPadding = new Thickness(1, 2, 3, 4);
var exception = Record.Exception(() => host.Page = second);
Assert.Null(exception);
Assert.Equal(default, first.SafeAreaPadding);
Assert.NotNull(host.Presenter);
Assert.Same(second, host.Presenter!.Child);
}
}
}

Loading…
Cancel
Save