總目錄
前言
本文介紹控件模板:
一、控件模板
二、模板綁定
環(huán)境
1.Visual Studio 2017
2.Xamarin.Froms 4.0.0.62955-pre2
3.Android 4.4(API 19)或更高版本
4.約定:XF代表Xamarin.Forms
內(nèi)容
一、控件模板
控件模板:控件模板將頁面與內(nèi)容分離,使用它很容易實現(xiàn)主題設計。
下面簡單實現(xiàn)日間/夜間主題切換。
實現(xiàn)效果


實現(xiàn)方式

在ControlTemplate中定義布局,以及布局內(nèi)包含的控件,使用ContentPresenter作為自定義內(nèi)容的占位符,即:自定義顯示內(nèi)容的顯示位置;

1.在帶有ControlTemplate屬性的控件或頁面上應用ControlTemplate。
2.帶有ControlTemplate屬性的控件或頁面:
- ContentPage:內(nèi)容頁面;
- ContentView:內(nèi)容視圖;
- TemplatedPage:ContentPage的基類,沒有Content屬性,所以只能通過控件模板添加內(nèi)容;
- TemplatedView:ContentView的基類,沒有Content屬性,所以只能通過控件模板添加內(nèi)容;

二、模板綁定
模板綁定:模板綁定(TemplateBinding)可以讓控件模板中的控件將數(shù)據(jù)綁定到公共屬性,使之動態(tài)變化。
上述控件模板中的標題,寫死在了控件模板中,下面通過模板綁定,使其綁定到其它屬性,使之可以靈活修改。
實現(xiàn)效果

實現(xiàn)方式(主要代碼)


新建MainPageViewModel類,并將MainPage的BindingContext綁定到它的實例。

1.使用TemplateBinding綁定到Title屬性。
2.TemplateBinding類似于Binding,區(qū)別在于:TemplateBinding的源為控件模板所屬的控件或頁面。例如:本例中TemplateBinding的源為ContentView,而ContentView的Parent為ContentPage,所以模板綁定到Parent.BindingContext.Title,即:ContentPage的BindingContext的Title。
3.TemplateBinding只能在ControlTemplate中使用。
后語
下篇介紹數(shù)據(jù)模板,待續(xù)...