简体   繁体   English

如何在 C# ContentPage 中访问我的 App.xaml 上的静态资源模板?

[英]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?如何在 C# ContentPage 中访问我的 App.xaml 上的静态资源模板?

This is my code.这是我的代码。 The App.xaml: 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.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:和 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...我需要访问 lbl_title object 不仅是 his.Text 属性,还有他的颜色、背景等...

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.要获取 ControlTemplate 中的元素,可以尝试将页面强制转换为IPageController并使用 foreach 遍历其中包含的控件。

MainPage.cs主页.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 .或者调用TemplatedPage.GetTemplateChild(String) Method This method is use to "Retrieves the named element in the instantiated ControlTemplate visual tree".此方法用于“在实例化的 ControlTemplate 可视化树中检索命名元素”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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