echo("備忘録");

IT技術やプログラミング関連など、技術系の事を備忘録的にまとめています。

【Xamarin.Forms】コントロールのスタイルを設定する

Xamarin.Formsでラベルやボタンなどのスタイルを設定する方法。
(Windows Formなら「プロパティ」で簡単に設定できるんだけど...)

XAMLの場合

「ResourceDictionary」を使用する。

    <ContentPage.Resources>
        <ResourceDictionary>
            <Style x:Key="ButtonRedStyle" TargetType="Button">
                <Setter Property="TextColor" Value="Black" />
                <Setter Property="BackgroundColor" Value="Red" />
                <Setter Property="BorderColor" Value="Black" />
                <Setter Property="BorderWidth" Value="2" />
                <Setter Property="BorderRadius" Value="0" />
            </Style>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout>
            <Button x:Name="button_red" Text="Red" Style="{StaticResource ButtonRedStyle}" />
        </StackLayout>
    </ContentPage.Content>

結果:
f:id:Makky12:20180412102843j:plain

ResourceDictionaryでスタイル及び「x:Key」を設定して、それをコントロール側で「style="{StaticResource xxx}"」で参照する。

C#で直書きする場合

            var buttonBlueStyle = new Style(typeof(Button))
            {
                Setters = {
                    new Setter { Property = Button.TextColorProperty, Value = Color.White },
                    new Setter { Property = Button.BackgroundColorProperty, Value = Color.Blue },
                    new Setter { Property = Button.BorderColorProperty, Value = Color.Black },
                    new Setter { Property = Button.BorderWidthProperty, Value = 2 },
                    new Setter { Property = Button.BorderRadiusProperty, Value = 0 },
                }
            };

            var blueButton = new Button
            {
                Text = "Blue",
                Style = buttonBlueStyle,
            };

            var stackLayout = new StackLayout
            {
                Children =
                {
                    blueButton
                },
            };
            
            this.Content = stackLayout;

結果:
f:id:Makky12:20180412102836j:plain

C#の場合は「Style」クラスで普通に参照する。

ちなみに、これはページ毎に設定してますが、全ページ共通のスタイルにする場合、AppクラスにStyleを定義すれば、共通スタイルとして定義できる。
参照:Xamarin.Forms で Style を利用する - Xamarin 日本語情報

※公式サイト(Xamarin Documentation - Xamarin | Microsoft Docs)ではC#(コードビハインド)で書かれているので、コードビハインドで記述するのが良いのかも...


昔に比べて、だいぶ良くなってきたとはいえ、まだまだXamarinは改良してほしい点が多いですね。