1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Xamarin.Formsで各コントロールに共通のスタイルを適用する方法(2)

Posted at

概要

(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>

表示結果

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?