概要
(1)の続編なので、まずは前編を読んでいない場合は前編を参照して欲しい。
ここでは、共通スタイルをControlTemplateの仕組みを使って実装する。
今回は、ControlTemlateに各コントロールのスタイルを定義することによって、各画面のコントロールのスタイルを共通化する方法を紹介する。
ControlTemplate用にContentPageを作成する
Controlsフォルダーを右クリックして「追加」「新しい項目...」をクリックして表示されるダイアログで「コンテンツページ」を選択して名前に「MyTemplatePage.xaml」を入力して「追加」をクリック。
作成された「MyTemplatePage.xaml」で次の通り入力する。
下記の入力により「Label」コントロールのデフォルトのスタイルを適用できる。
MyTemplatePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="CustomeControlTest.Controls.MyTemplatePage">
<ContentPage.Resources>
<Style TargetType="Label">
<Setter Property="FontSize" Value="26" />
<Setter Property="TextColor" Value="Black" />
<Setter Property="BackgroundColor" Value="GreenYellow" />
</Style>
</ContentPage.Resources>
</ContentPage>
MainPage.xamlは次のように書き換える。
まず、ルート要素をMyTemplatePageを使用するように書き換える。
名前空間は、「xmlns:controls」でMyTemplatePageを参照可能なように指定する。
ルート要素の「controls:MyTemplatePage」を指定することでこのページのテンプレートとしてMyTemplatePageが参照される。
MainPage.xaml
<?xml version="1.0" encoding="UTF-8"?>
<controls:MyTemplatePage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:CustomeControlTest.Controls"
x:Class="CustomeControlTest.MainPage"
Title="Access template element demo"
>
<StackLayout Margin="20, 20, 20, 0" BackgroundColor="LightBlue">
<StackLayout Orientation="Horizontal">
<Label x:Name="Label1" Text="222" WidthRequest="200" />
<Entry Text="入力"/>
</StackLayout>
<StackLayout Orientation="Horizontal">
<Label x:Name="Label2" Text="Test2" WidthRequest="200" />
<Entry Text="入力"/>
</StackLayout>
</StackLayout>
</controls:MyTemplatePage>
表示結果
