Xamarin XAML语言中如何实现控件模板的模板绑定

免费建站   2024年05月10日 23:06  

这篇文章主要介绍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),

".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实例。

以上是“Xamarin XAML语言中如何实现控件模板的模板绑定”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注行业资讯频道!

域名注册
购买VPS主机

您或许对下面这些文章有兴趣:                    本月吐槽辛苦排行榜

看贴要回贴有N种理由!看帖不回贴的后果你懂得的!


评论内容 (*必填):
(Ctrl + Enter提交)   

部落快速搜索栏

各类专题梳理

网站导航栏

X
返回顶部