Xamarin XAML语言教程控件模板的模板绑定
控件模板的模板绑定
为了可以轻松更改控件模板中控件上的属性值,可以在控件模板中实现模板绑定功能。模板绑定允许控件模板中的控件将数据绑定到公共属性上。这时需要使用TemplateBinding。它可以将控件模板中的控件的属性绑定到拥有控件模板的目标视图的父级上的可绑定属性上。
注意:(1)TemplateBinding类似于现有的Binding,不同之处在于TemplateBinding的源总是自动设置为拥有控件模板的目标视图的父级。(2)不支持在控件模板之外使用TemplateBinding。
【示例14-5:ControlTemplateDemo】以下将以项目ControlTemplateDemo为基础,在控件模板中实现模板绑定功能。具体的操作步骤如下:
(1)打开MainPage.xaml文件,编写代码,实现可绑定属性的定义。代码如下:
-
namespace ControlTemplateDemo
-
{
-
public partial class MainPage : ContentPage
-
{
-
bool originalTemplate = true;
-
ControlTemplate tealTemplate;
-
ControlTemplate aquaTemplate;
-
public static readonly BindableProperty HeaderTextProperty = BindableProperty.Create("HeaderText",
-
typeof(string),
-
typeof(MainPage),
-
"Knowledge is power.");
-
public static readonly BindableProperty FooterTextProperty = BindableProperty.Create("FooterText",
-
typeof(string),
-
typeof(MainPage),
-
"Xamarin.Froms XAML");
-
public MainPage()
-
{
-
InitializeComponent();
-
…… //此处省略了对tealTemplate和aquaTemplate对象的实例化
-
}
-
public string HeaderText
-
{
-
get
-
{
-
return (string)GetValue(HeaderTextProperty);
-
}
-
}
-
public string FooterText
-
{
-
get
-
{
-
return (string)GetValue(FooterTextProperty);
-
}
-
}
-
…… //此处省略了对OnButtonClicked方法的实现
-
}
-
}
(2)打开App.xaml文件,编写代码,在第一个构建的ControlTemplate中实现模板绑定功能。代码如下:
-
<ControlTemplate x:Key="TealTemplate">
-
<Grid>
-
<Grid.RowDefinitions>
-
<RowDefinition Height="0.1*" />
-
<RowDefinition Height="0.8*" />
-
<RowDefinition Height="0.1*" />
-
</Grid.RowDefinitions>
-
<Grid.ColumnDefinitions>
-
<ColumnDefinition Width="0.05*" />
-
<ColumnDefinition Width="0.95*" />
-
</Grid.ColumnDefinitions>
-
<BoxView Grid.ColumnSpan="2"
-
Color="Teal" />
-
<Label Grid.Column="1"
-
Text="{TemplateBinding Parent.HeaderText}"
-
TextColor="White"
-
FontSize="18"
-
VerticalOptions="Center" />
-
<ContentPresenter Grid.Row="1"
-
Grid.ColumnSpan="2" />
-
<BoxView Grid.Row="2"
-
Grid.ColumnSpan="2"
-
Color="Teal" />
-
<Label Grid.Row="2"
-
Grid.Column="1"
-
Text="{TemplateBinding Parent.FooterText}"
-
TextColor="White"
-
FontSize="18"
-
VerticalOptions="Center" />
-
</Grid>
-
</ControlTemplate>
在此代码中,我们将两个Label控件的Text属性实现了模板绑定功能,在上文中我们提到了属性使用模板绑定将其绑定到拥有ControlTemplate的目标视图的父级上的可绑定属性上。但是,在我们的代码中,模板绑定绑定到Parent.HeaderText和Parent.FooterText上,而不是HeaderText和FooterText上。这是因为在此代码中,可绑定属性是在目标视图的祖父级上定义的,而不是父级。
注意:模板绑定的源始终自动设置为拥有控件模板的目标视图的父级,在此项目中是ContentView实例。模板绑定使用Parent属性返回ContentView实例的父元素,这是ContentPage实例。
此时运行程序,会看到和图14.12~14.14一样的运行效果。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29597077/viewspace-2142582/
,如需转载,请注明出处,否则将追究法律责任。