【发布时间】:2020-12-04 05:50:21
【问题描述】:
我想创建一个可重用的模板页面,我想在整个应用程序中使用它。
我决定使用ControlTemplate 来实现这一目标,但我遇到了问题。第一个问题是HeaderText 绑定到它时不会显示。第二个问题是使用这个 ControlTemplate 的 Page 没有他的孩子可见,ContentPresenter 是空的。
控制模板:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Project.MainViewTemplate">
<ContentPage.ControlTemplate>
<ControlTemplate>
<Grid RowSpacing="0">
<Grid.RowDefinitions>
<RowDefinition Height="2*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Label TextColor="Black"
Text="{TemplateBinding HeaderText}"
BackgroundColor = "Green"
Grid.Row="0"/>
<ContentPresenter Grid.Row="1"/>
</Grid>
</ControlTemplate>
</ContentPage.ControlTemplate>
及其背后的代码:
public partial class MainViewTemplate : ContentPage
{
public static readonly BindableProperty HeaderTextProperty = BindableProperty.Create(nameof(HeaderText), typeof(string), typeof(MainViewTemplate), default(string));
public string HeaderText
{
get { return (string)GetValue(HeaderTextProperty); }
set { SetValue(HeaderTextProperty, value); }
}
public MainViewTemplate()
{
InitializeComponent();
}
}
使用它的页面:
<template:MainViewTemplate xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Project.MainView"
xmlns:template="clr-namespace:Project"
HeaderText="Main view">
<StackLayout Margin="10"
BackgroundColor="Green">
<Label Text = "Test"/>
</StackLayout>
</template:MainViewTemplate>
绑定HeaderText 的标签未显示其文本,如果我将其更改为编写硬编码文本,它可以工作,因此绑定出现问题。其次,我也可以看到绿色背景。其次,contentpresenter 没有显示使用此 ControlTemplate 的页面内的内容。
【问题讨论】:
-
嘿,您发布的代码没有任何问题。您是在 Android 还是 iOS 上运行它?
-
iOS,但尚未在 android 上测试过 @pinedax。
标签: c# xamarin xamarin.forms