Search code examples
xamarin.formsxamarin.uwpcustom-renderer

In Forms UWP, back navigation with content view in custom title view not working correct with custom renderer


Description

When using custom renderer for the content view. It throws "Element is already the child of another element" while converting the content of the content view to the content presenter using the content control.

Steps to Reproduce

  1. Run the attached sample.
  2. Navigate to the sub page and navigate back.
  3. Content view gets hidden and page not navigated back properly.
  4. Exception gets thrown in the on element changed method of custom renderer.

Expected Behavior

Page should be navigated back properly with the content view as like the second time.

Actual Behavior

In first time page is not navigated back properly and also content view gets disappear.

Screenshots

  • Actual Output

image

  • Expected Output

image

Workaround

Please check the below sample. CustomControl.zip

Can anyone help me with this?


Solution

  • Element is already the child of another element"

    The problem is your CustomView has been referenced by previous view, when you navigation back, the navigation create new ContentPage that want to use previous CustomView, but the previous CustomView has not be released. For solving this problem, you could set TitleViewProperty as null when page OnDisappearing.

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        SetValue(NavigationPage.TitleViewProperty, null);
    }
    

    Update

    Please set TitleViewProperty in OnAppearing method like the following.

    protected override void OnAppearing()
    {
        base.OnAppearing();
        SetValue(NavigationPage.TitleViewProperty, new NavigationView());
    }
    
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        SetValue(NavigationPage.TitleViewProperty, null);
    }