如何在 C# ContentPage 中访问 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>
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 属性,还有他的颜色、背景等......
这是控制模板:
<ControlTemplate x:Key="template">
<StackLayout>
<Label x:Name="lbl_title" Text="test"/>
<Button />
</StackLayout>
</ControlTemplate>
要获取 ControlTemplate 中的元素,可以尝试将页面IPageController
强制转换为并使用 foreach 遍历其包含的控件。
主页.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) 方法。此方法用于“检索实例化的 ControlTemplate 可视化树中的命名元素”。
Label myControl = this.GetTemplateChild("lbl_title") as Label;
myControl.Text = "new test text";
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句