【问题标题】:How could I accese in C# ContentPage, to a StaticResource Template on my App.xaml?如何在 C# ContentPage 中访问我的 App.xaml 上的 StaticResource 模板?
【发布时间】:2021-05-11 08:31:09
【问题描述】:

如何在 C# ContentPage 中访问我的 App.xaml 上的 StaticResource 模板?

这是我的代码。 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>

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>

还有 ContentPage.cs:

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

我需要访问 lbl_title 对象,而不仅仅是他的 .Text 属性,还有他的颜色、背景等...

【问题讨论】:

    标签: c# xaml xamarin xamarin.forms xamarin.android


    【解决方案1】:

    这里是 ControlTemplate:

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

    要获取 ControlTemplate 中的元素,可以尝试将页面强制转换为 IPageController 并使用 foreach 遍历其中包含的控件。

    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;
                }
            }
        }
        // ...
    }
    

    更新:

    或致电TemplatedPage.GetTemplateChild(String) Method。此方法用于“在实例化的 ControlTemplate 可视化树中检索命名元素”。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-12
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      相关资源
      最近更新 更多