PG.Lib

アプリ開発関連とかガジェット関連とか

Xamarin.Forms で Style を Resource から読み込んでみる

UWPなXAMLと同じように、タグのプロパティを共通化するために、Resourceへ入れておき、Styleで簡単に設定することができます。

アプリケーション全体の場合で紹介します。

Resource の準備

App.xaml を開きます。

プロジェクト作り立てだと、Application.Recouces の中に

<!-- Application resource dictionary -->

とご丁寧に書かれてますので、こちらに追記していきます。

<Style x:Key="baseLabel" TargetType="Label">
    <Setter Property="HorizontalTextAlignment" Value="Center" />
    <Setter Property="VerticalTextAlignment" Value="Center" />
    <Setter Property="TextColor" Value="Black" />
</Style>

x:Key にはスタイルの名前を入れておきます。

TargetType には対象となるコントロールの種類を入れます。この場合はラベルですね。

プロパティ1つごとに、Setterタグを書いていきます。

Property にはプロパティ名。Value には値を入れます。

Style を設定する

<Label Grid.Column="0" Grid.Row="0" Text="1" 
        Style="{StaticResource baseLabel}"
        BackgroundColor="Blue" 
        FontSize="Large">
</Label>

Style プロパティへ StaticResource として、先ほど設定したスタイル名を入れます。

デザインを統一するうえで、設定内容を1か所にまとめておくと、コード量、見やすいさ含めて便利ですよね。