Taoffi's blog

prisonniers du temps

Xamarin forms: Traversing the View tree

 

It is sometimes necessary to find the parent of a View element.

Imagine you have a navigation control (a menu for instance) in which each button gives access to a specific page.

What if the target page is the current displayed one? (If a copy of this navigation control is, for instance, inserted inside this same page)

It would be useless (and maybe rather ugly, confusing and probably troublesome!) to try to display (push) the current page on itself.

In that case, it would be good to know if one of the ascendants of the control is this target page before trying to do the navigation.

A simple helper method can do this for us:

//
// Try to find an ascendant (parent) of type T
public static T GetParentPage<T>(View control) where T : ContentPage
{
    if(control == null)
        return null;

    var        parent    = control.Parent;

    while(parent != null)
    {
        if(parent is T)
            return parent as T;

        parent = parent.Parent;
    }
    return null;
}


Usage example:

 

//
var currentPage = UiHelpers.GetParentPage<CompanyPage>(this);

// It is alreay on screen: do nothing
if(currentPage != null)
    return;

// push a new page
await Navigation.PushAsync(new CompanyPage())

 

Searching a descendant is a little trickier… because one same page may contain several instances of one same ContentView (control). Combined with a specific BindingContext, that can be more effective. Something like:

//
public static T GetChildCntrol<T>(View control, object BindindingContext) where T : ContentView

 

You may try to play with this… Good luckJ

Comments are closed