概要
Xamarin.Formsでカスタムコントロールを使用すると、そのカスタムコントロールを張り付けた画面のプレビューの表示に失敗することが多くなる。これを回避するために、カスタムコントロールをC#のソースコードのみで作成するのではなく、XAML + コードビハインドで作成する。
環境
環境はこちらのページを参照してください。
コントロールの追加
共通プロジェクトの「Controls」フォルダーを右クリックして「追加」「新しい項目を追加...」をクリックして表示されるダイアログで、「コンテンツビュー」を選択して、名前に「MyLabelControl.xaml」を入力して「追加」をクリックする。
MyLabelControl.xamlを次のように編集する。
<?xml version="1.0" encoding="UTF-8"?>
<Label 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"
FontSize="26"
TextColor="Black"
BackgroundColor="Aqua"
x:Class="CustomeControlTest.Controls.MyLabelControl">
</Label>
ポイント
x:Classの指定は名前空間とクラス名なので、各環境に合わせて修正が必要となる。
FontSize、TextColor、BackgroundColorはこのカスタムコントロールの既定値として設定したい値をLabel要素の属性として追加する。
コードビハインドの修正
コードビハインドの「MyLabelControl.xaml.cs」は継承元をContentPageからLabelに変更する。
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CustomeControlTest.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MyLabelControl : Label
{
public MyLabelControl()
{
InitializeComponent();
}
}
}
以上で、コントロールの作成は完了
利用側ソース
MainPage.xamlで次のようにコントロールを利用する
<?xml version="1.0" encoding="UTF-8"?>
<controls:TemplatePage 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"
NavigationPage.HasNavigationBar="False"
HeaderText="Main"
FooterText="My Footer"
ControlTemplate="{StaticResource MyTemplate}"
>
<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 Orientation="Horizontal">
<controls:MyLabelControl Text="AAA" BackgroundColor="Red"/>
</StackLayout>
</StackLayout>
</controls:TemplatePage>
これにより、Visual StudioでMainPageのプレビューが正常に描画される。

実行結果
なお、コントロールのデフォルトの属性値の設定はMyLabelControl.xaml.csのコンストラクタ内でも設定可能だが、こちらのコードビハインドで実施すると、プレビューが正常に出来なくなる。