简体   繁体   中英

How could I accese in C# ContentPage, to a StaticResource Template on my App.xaml?

How could I accese in C# ContentPage, to a StaticResource Template on my App.xaml?

This is my code. The App.xaml:

 <Application xmlns="http://xamarin.com/schemas/2014/forms"
              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" >
    <Application.Resources>
        <ControlTemplate x:Key="template">
             ...
             <Label Text="{Binding lbl_title}" Grid.Row="0"/>
                        
             <!--Body -->
             <ContentPresenter Grid.Row="1"/>
             ...
        </ControlTemplate>
    </Application.Resources>
</Application>

The ContentPage.xaml:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             ControlTemplate="{StaticResource template}">

    <Grid x:Name="body_grid"/>
</ContentPage>

And the ContentPage.cs:

public partial class MenuPage : ContentPage{
   public MenuPage() {
       lbl_title.Text = "Title"; //This throw me and ERROR
       ... // Grid definition
   }
}

I need to accese to the lbl_title object not just his.Text property, also his color, background, etc...

Here is ControlTemplate:

<ControlTemplate x:Key="template">
    <StackLayout>
        <Label x:Name="lbl_title" Text="test"/>
        <Button />
    </StackLayout>
</ControlTemplate>

To get the elements in ControlTemplate, you can try to cast the page to IPageController and use foreach to traverse the controls it contains.

MainPage.cs

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        var controller = this as IPageController;
        foreach (var child in controller.InternalChildren)
        {
            var result = child.FindByName<Label>("lbl_title");
            if (result != null)
            {
                Label myControl = result;
                myControl.Text = "new text";
                myControl.BackgroundColor = Color.Red;
            }
        }
    }
    // ...
}

Update:

Or call the TemplatedPage.GetTemplateChild(String) Method . This method is use to "Retrieves the named element in the instantiated ControlTemplate visual tree".

Label myControl = this.GetTemplateChild("lbl_title") as Label;
myControl.Text = "new test text";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM