Xamarin.Formsでコントロールの見た目をResourceDictionaryで指定する
CSSと同様に,コントロールの見た目を予め定義し,それを各コントロールに指定することで,見た目を変更することができます.
基本的にはResourceDictionaryにStyleとして定義して使用します.
これによって同じ見た目の定義を1回行うだけで,同じ見た目のコントロールを作成することができ,UI作成,編集の効率が上がります.
例えば,以下のような見た目のラベルを作る場合,このコントロール1つだけであれば以下のようにするでしょう.
<Label BackgroundColor="LightBlue" FontSize="Large" HorizontalOptions="CenterAndExpand" Text="Label1" TextColor="LightPink" VerticalOptions="CenterAndExpand" />
しかし,同じ見た目のラベルを複数用意する場合,すべてのラベルに上記の指定を行うのは手間です.
また,見た目を変更する際にすべてのラベルに対して変更を行わなければならず,手間であるとともに変更の見落としも発生しやすくなります.
そこで,以下のようにStyleとして予め定義しておくことで,見た目の指定が容易になります.
<ContentPage x:Class="XFStylePractice.MainPage" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:d="http://xamarin.com/schemas/2014/forms/design" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <ContentPage.Resources> <ResourceDictionary> <Style x:Key="labelStyle" TargetType="Label"> <Setter Property="BackgroundColor" Value="LightBlue" /> <Setter Property="FontSize" Value="Large" /> <Setter Property="HorizontalOptions" Value="CenterAndExpand" /> <Setter Property="VerticalOptions" Value="CenterAndExpand" /> <Setter Property="TextColor" Value="LightPink" /> </Style> </ResourceDictionary> </ContentPage.Resources> <StackLayout> <Label BackgroundColor="LightBlue" FontSize="Large" HorizontalOptions="CenterAndExpand" Text="Label1" TextColor="LightPink" VerticalOptions="CenterAndExpand" /> <Label Style="{StaticResource labelStyle}" Text="Label2" /> <Label Style="{StaticResource labelStyle}" Text="Label3" /> <Label Style="{StaticResource labelStyle}" Text="Label4" /> <Label Style="{StaticResource labelStyle}" Text="Label5" /> </StackLayout> </ContentPage>
Style指定の種類
Styleの定義,指定の仕方にはざっくりわけて明示的な指定と暗黙的な指定の2種類があります.
明示的な指定
ResourceDictionaryにStyleとして定義し,そのStyleに名前(x:Key)をつけておき,コントロール側で適用したいStyleを名前で指定します.対象とするコントロールの種類(TargetType)は必須です.
CSSで言えばclass属性でスタイルを指定するのと同じです.
上の例は,この明示的な指定になります.
暗黙的な指定
ResourceDictionaryにStyleを定義しますが,ここでは対象とするコントロールの種類だけを指定し,名前はつけません.指定したコントロールに自動的にそのStyleが適用されます.
使い方
明示的な指定
冒頭の例のとおりです.
暗黙的な指定
こちらはResourceDictionary内でのStyleの定義の際にx:Key
を指定しません.
<Style TargetType="Label"> <Setter Property="BackgroundColor" Value="LightBlue" /> <Setter Property="FontSize" Value="Large" /> <Setter Property="HorizontalOptions" Value="CenterAndExpand" /> <Setter Property="VerticalOptions" Value="CenterAndExpand" /> <Setter Property="TextColor" Value="LightPink" /> </Style>
そして,Labelを配置する際に,明示的な指定とは異なり,適用するStyleを指定しません.
<StackLayout> <Label Text="Label1" /> <Label Text="Label2" /> <Label Text="Label3" /> <Label Text="Label4" /> <Label Text="Label5" /> </StackLayout>
明示的な指定はTargetTypeで指定したコントロールの種類に対して一律で適用されます.