How to access the elements of a ControlTemplate in Xamarin Forms

自闭症网瘾萝莉.ら 提交于 2019-12-01 02:29:57

问题


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

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

Does Xamarin provide a way to peek into the contents of a ControlTemplate?


回答1:


If you have Page instance you can cast it to IPageController and it's InternalChildren property contains controls from the template.

Here is an extension method I'm using 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;
}



回答2:


I havent found a way yet to iterate through the control template children. I used template binding https://developer.xamarin.com/guides/xamarin-forms/templates/control-templates/template-binding/ to bind to a command object, the properties for the commands are defined in my base page, then used a base view to define my commands and set them to the binding backing properties in the basepage OnAppearing override.

I am working on a blog entry and will update this when I have code to show.




回答3:


Although this is a old topic but the actual Xamarin Forms API provides the following and works out of the box:

contentView.GetTemplateChild("nameOfTheControl")


来源:https://stackoverflow.com/questions/38690562/how-to-access-the-elements-of-a-controltemplate-in-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!