How to access ControlTemplate elements in Xamarin formats

I have a ControlTemplate defined in App.xaml. Now I need to be able to handle certain user interface events. In the Visual Studio XAML editor, if I attach a handler to an event, the handler is created in App.xaml.cs. However, I need to do this on pages that use this control pattern.

I think the only way is to iterate over the elements in the control template and find the desired element and create handlers on the pages. However, I'm not sure how to access the elements from the ControlTemplate object.

Does Xamarin provide a glimpse into the contents of a ControlTemplate?

+7
source share
3 answers

If you have a Page instance, you can apply it to the IPageController , and the InternalChildren property contains the controls from the template.

Here is the extension method that I use to find controls by name

public static T FindTemplateElementByName<T> (this Page page, string name) where T: Element { var pc = page as IPageController; if (pc == null) { return null; } foreach (var child in pc.InternalChildren) { var result = child.FindByName<T> (name); if (result != null) { return result; } } return null; } 
+3
source

I havent found a way to still iterate through the children of the control template. I used the template binding https://developer.xamarin.com/guides/xamarin-forms/templates/control-templates/template-binding/ to bind the command object, the properties for the commands are defined on my base page, and then the base views for defining my commands and their binding to the binding binding properties on the OnAppearing override base page.

I am working on a blog post and updating it when I have code to display.

+1
source

Although this is an old topic, the actual Xamarin forms API provides the following and works out of the box:

 contentView.GetTemplateChild("nameOfTheControl") 
0
source

All Articles