Xamarin XAML語言教程構建ControlTemplate控制元件模板 (四)

大學霸發表於2017-07-19

Xamarin XAML語言教程構建ControlTemplate控制元件模板 (四)

2.在頁面級別中構建控制元件模板

如果開發者要在頁面級別中構建控制元件模板,首先必須將ResourceDictionary新增到頁面中,然後在ResourceDictionary中實現模板的構建即可,其語法形式如下:


  • <Page>
  • <Page.Resources>
  • <ResourceDictionary>
  • <ControlTemplate x:Key="KeyName">
  • ……
  • </ControlTemplate>
  • </ResourceDictionary>
  • </Page.Resources>
  • </Page>


其中,Page表示的是頁面以及頁面的子類。KeyName用來指定一個字典鍵,此鍵指代的就是控制元件模板。

【示例14-4ControlTemplateContentPage】以下將在內容頁面中構建控制元件模板。程式碼如下:


  • <?xml version="1.0" encoding="utf-8" ?>
  • <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
  •              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  •              xmlns:local="clr-namespace:ControlTemplateContentPage"
  •              x:Class="ControlTemplateContentPage.MainPage">
  •   <ContentPage.Resources>
  • <ResourceDictionary>
  • <!--構建控制元件模板-->
  •       <ControlTemplate x:Key="TealTemplate">
  •         <StackLayout VerticalOptions="CenterAndExpand"
  •                      Spacing="20"
  •                      Padding="20">
  •           <Entry Placeholder="Username" />
  •           <Entry Placeholder="Password"
  •                  IsPassword="True"/>
  •           <Button Text="Click Here To Log In"   />
  •           <ContentPresenter />
  •         </StackLayout>
  •       </ControlTemplate>
  •     </ResourceDictionary>
  •   </ContentPage.Resources>
  •   <ContentView x:Name="contentView"
  •              Padding="0,20,0,0"
  •              ControlTemplate="{StaticResource TealTemplate}">
  •     <Frame OutlineColor="Accent">
  •       <Label Text="請在確認環境安全後,輸入賬號和對應的密碼"
  •              FontAttributes="Bold"
  •              FontSize="18"/>
  •     </Frame>
  •   </ContentView>
  • </ContentPage>


此時執行程式,會看到如圖14.18~14.20所示的效果。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29597077/viewspace-2142271/,如需轉載,請註明出處,否則將追究法律責任。

相關文章