Xamarin Community Toolkit C# マークアップ

サンプルをダウンロードします。 Xamarin.CommunityToolkit.MarkupSample をダウンロードする

C# マークアップは、C# で宣言型 Xamarin.Forms ユーザー インターフェイスを構築するプロセスを簡略化するための、Fluent ヘルパー メソッドとクラスのセットです。 C# マークアップによって提供される fluent API は、名前空間で Xamarin.CommunityToolkit.Markup 使用できます。

XAML と同様に、C# マークアップを使用すると、UI マークアップと UI ロジックを完全に分離できます。 これは、UI マークアップと UI ロジックを個別の部分クラス ファイルに分離することで実現できます。 たとえば、ログイン ページの場合、UI マークアップは LoginPage.cs という名前のファイル内にありますが、UI ロジックは LoginPage.logic.cs という名前のファイル内にあります。

最新バージョンの C# マークアップには Xamarin.Forms 5 が必要であり、 Xamarin.CommunityToolkit.Markup NuGet パッケージで入手できます。

C# マークアップは、Xamarin.Forms でサポートされているすべてのプラットフォームで使用できます。

Note

C# マークアップのプレビュー バージョンは、Xamarin.Forms 4.6 から 4.8 で試験的な機能として使用できます。

C# マークアップ プレビュー バージョンから XCT C# マークアップに移行するには:

  1. Xamarin.Forms フォーム 5 に更新します。
  2. Xamarin.CommunityToolkit.Markup NuGet パッケージをインストールします。
  3. 名前空間Xamarin.CommunityToolkit.Markupへのすべての参照をXamarin.Forms.Markup変更し、マークアップ ファイルに含めてくださいusing Xamarin.Forms;
  4. 必要に応じ、ヘルパー呼び出しを更新 Font します。 Fontfamilyの代わりにsize最初のパラメーターとして使用できるようになりました。 たとえば、次のように置き換えます.Font(15).Font(size: 15).FontSize(15)

C# マークアップのプレビュー バージョンを既に理解している場合は、以下の Xamarin Community Toolkit の追加機能 を参照してください。

基本的な例

次の例は、C# の a と 、を含むLabel新しいGridページ コンテンツにページコンテンツを設定する方法をEntry示しています。

Grid grid = new Grid();

Label label = new Label { Text = "Code: " };
grid.Children.Add(label, 0, 1);

Entry entry = new Entry
{
    Placeholder = "Enter number", Keyboard = Keyboard.Numeric, BackgroundColor = Color.AliceBlue, TextColor = Color.Black, FontSize = 15,
    HeightRequest = 44, Margin = fieldMargin
};
grid.Children.Add(entry, 0, 2);
Grid.SetColumnSpan(entry, 2);
entry.SetBinding(Entry.TextProperty, new Binding("RegistrationCode"));

Content = grid;

この例では、子LabelとオブジェクトをGrid含むオブジェクトをEntry作成します。 Label表示テキストとデータはEntryビューモデルのRegistrationCodeプロパティにバインドされます。 各子ビューは、内の特定の行Gridに表示されるように設定されEntryGrid、. さらに、キーボード、色、テキストの Entry フォント サイズ、および Margin. 最後に、プロパティが Page.Content オブジェクトに Grid 設定されます。

C# マークアップを使用すると、Fluent API を使用してこのコードを再作成できます。

Content = new Grid { Children =
{
    new Label { Text = "Code:" }
               .Row (BodyRow.CodeHeader) .Column (BodyCol.Header),

    new Entry { Placeholder = "Enter number", Keyboard = Keyboard.Numeric, BackgroundColor = Color.AliceBlue, TextColor = Color.Black } .FontSize (15)
               .Row (BodyRow.CodeEntry) .ColumnSpan (All<BodyCol>()) .Margin (fieldMargin) .Height (44)
               .Bind (nameof(vm.RegistrationCode))
}}};

この例は前の例と同じですが、C# マークアップ Fluent API を使用すると、C# で UI を構築するプロセスが簡略化されます。

Note

C# マークアップには、特定のビュー プロパティを設定する拡張メソッドが含まれています。 これらの拡張メソッドは、すべてのプロパティ セッターを置き換えることを意図したものではありません。 代わりに、コードの読みやすさを向上させるために設計されており、プロパティ セッターと組み合わせて使用できます。 プロパティに拡張メソッドが存在する場合は、常に拡張メソッドを使用することをお勧めしますが、任意の残高を選択できます。

名前空間の使用

C# マークアップを使用するには、マークアップ ファイルに次 using のステートメントを含めます。

using Xamarin.Forms;
using Xamarin.CommunityToolkit.Markup;

マークアップを次の目的で設計する場合:

  • LTR のみ: using Xamarin.CommunityToolkit.Markup.LeftToRight;
  • RTL のみ: using Xamarin.CommunityToolkit.Markup.RightToLeft;
  • LTR と RTL の両方: 含めたり名前空間をRightToLeftLeftToRightめたりしないでください

行と列を操作 Grid するには、次も含めます using static Xamarin.CommunityToolkit.Markup.GridRowsColumns;

データ バインディング

C# マークアップには、ビューバインド Bind 可能なプロパティと指定したプロパティの間にデータ バインディングを作成する拡張メソッドとオーバーロードが含まれています。 このメソッドは Bind 、Xamarin.Forms に含まれるほとんどのコントロールの既定のバインド可能なプロパティを認識します。 そのため、通常、このメソッドを使用するときにターゲット プロパティを指定する必要はありません。 追加のコントロールの既定のバインド可能なプロパティを登録することもできます。

DefaultBindableProperties.Register(
  HoverButton.CommandProperty,
  RadialGauge.ValueProperty
);

このメソッドを Bind 使用して、バインド可能なプロパティにバインドできます。

new Label { Text = "No data available" }
           .Bind (Label.IsVisibleProperty, nameof(vm.Empty))

さらに、拡張メソッドは BindCommand 、1 つのメソッド呼び出しでコントロールの既定値 CommandCommandParameter プロパティにバインドできます。

new TextCell { Text = "Tap me" }
              .BindCommand (nameof(vm.TapCommand))

既定では、 CommandParameter バインド コンテキストにバインドされます。 バインドのパスとソースとバインディングをCommandCommandParameter指定することもできます。

new TextCell { Text = "Tap Me" }
              .BindCommand (nameof(vm.TapCommand), vm, nameof(Item.Id))

この例では、バインディング コンテキストは Item インスタンスであるため、バインディングのソース IdCommandParameter を指定する必要はありません。

バインドCommandする必要がある場合は、メソッドのBindCommand引数にparameterPathnullすことができます。 または、このメソッドを使用します Bind

追加のコントロールの既定値 CommandCommandParameter プロパティを登録することもできます。

DefaultBindableProperties.RegisterCommand(
    (CustomViewA.CommandProperty, CustomViewA.CommandParameterProperty),
    (CustomViewB.CommandProperty, CustomViewB.CommandParameterProperty)
);

インライン コンバーター コードは、次のパラメーターを使用してBindメソッドにconvertBackconvert渡すことができます。

new Label { Text = "Tree" }
           .Bind (Label.MarginProperty, nameof(TreeNode.TreeDepth),
                  convert: (int depth) => new Thickness(depth * 20, 0, 0, 0))

型セーフ なコンバーター パラメーターもサポートされています。

new Label { }
           .Bind (nameof(viewModel.Text),
                  convert: (string text, int repeat) => string.Concat(Enumerable.Repeat(text, repeat)))

さらに、コンバーター コードとインスタンスは、クラスで FuncConverter 再利用できます。

FuncConverter<int, Thickness> treeMarginConverter = new FuncConverter<int, Thickness>(depth => new Thickness(depth * 20, 0, 0, 0));
new Label { Text = "Tree" }
           .Bind (Label.MarginProperty, nameof(TreeNode.TreeDepth), converter: treeMarginConverter),

このクラスでは FuncConverter 、オブジェクトもサポートされています CultureInfo

cultureAwareConverter = new FuncConverter<DateTimeOffset, string, int>(
    (date, daysToAdd, culture) => date.AddDays(daysToAdd).ToString(culture)
);

また、プロパティで指定されたFormattedTextオブジェクトにSpanデータをバインドすることもできます。

new Label { } .FormattedText (
    new Span { Text = "Built with " },
    new Span { TextColor = Color.Blue, TextDecorations = TextDecorations.Underline }
              .BindTapGesture (nameof(vm.ContinueToCSharpForMarkupCommand))
              .Bind (nameof(vm.Title))
)

ジェスチャ認識エンジン

CommandプロパティにはCommandParameter、データにGestureElementバインドしView、拡張メソッドをBindClickGestureBindSwipeGestureBindTapGesture使用して型を指定できます。

new Label { Text = "Tap Me" }
           .BindTapGesture (nameof(vm.TapCommand))

次の使用例は、指定した型のジェスチャ認識エンジンを作成し、それを Label. 拡張メソッドは Bind*Gesture 、拡張メソッドと同じパラメーターを BindCommand 提供します。 ただし、既定では Bind*Gesture バインド CommandParameterされませんが、バインドは BindCommand 行われません。

パラメーターを使用してジェスチャ認識エンジンを初期化するには、次のClickGestureメソッド 、PanGesture、、PinchGestureSwipeGestureおよびTapGesture拡張メソッドを使用します。

new Label { Text = "Tap Me" }
           .TapGesture (g => g.Bind(nameof(vm.DoubleTapCommand)).NumberOfTapsRequired = 2)

ジェスチャ認識エンジンは 1 BindableObjectつであるため、初期化時に Bind メソッドと BindCommand 拡張メソッドを使用できます。 拡張メソッドを使用して、カスタム ジェスチャ認識エンジンの種類を Gesture<TGestureElement, TGestureRecognizer> 初期化することもできます。

Layout

C# マークアップには、レイアウト内のビューとビュー内のコンテンツの配置をサポートする一連のレイアウト拡張メソッドが含まれています。

種類 拡張メソッド
FlexLayout AlignSelf, Basis, Grow, Menu, Order, Shrink
Grid Row, Column, RowSpan, ColumnSpan
Label TextLeft, TextCenterHorizontal, TextRight
TextTop, TextCenterVertical, TextBottom
TextCenter
IPaddingElement (例: Layout) Padding, Paddings
LayoutOptions Left, CenterHorizontal, FillHorizontal, Right
LeftExpand, CenterExpandHorizontal, FillExpandHorizontal, RightExpand
Top, Bottom, CenterVertical, FillVertical
TopExpand, BottomExpand, CenterExpandVertical, FillExpandVertical
Center, Fill, CenterExpand, FillExpand
View Margin, Margins
VisualElement Height, Width, MinHeight, MinWidth, Size, MinSize

左から右および右から左へのサポート

左から右 (LTR) または右から左 (RTL) のフロー方向をサポートするように設計された C# マークアップの場合、上に示した拡張メソッドは最も直感的な名前Leftのセットを RightTopBottom提供します。

適切な左右の拡張メソッドのセットを使用できるようにし、そのプロセスでマークアップが設計されているフロー方向を明示的にするには、次の 2 つのusingディレクティブusing Xamarin.CommunityToolkit.Markup.LeftToRight;using Xamarin.CommunityToolkit.Markup.RightToLeft;のいずれかを含めます。

左から右と右から左の両方のフロー方向をサポートするように設計された C# マークアップの場合は、上記のいずれかの名前空間ではなく、次の表の拡張メソッドを使用することをお勧めします。

種類 拡張メソッド
Label TextStart, TextEnd
LayoutOptions Start, End
StartExpand, EndExpand

レイアウト線の規則

推奨される規則は、ビューのすべてのレイアウト拡張メソッドを次の順序で 1 行に配置することです。

  1. ビューを含む行と列。
  2. 行と列内の配置。
  3. ビューの周囲の余白。
  4. 表示サイズ。
  5. ビュー内のパディング。
  6. パディング内のコンテンツの配置。

次のコードは、この規則の例を示しています。

new Label { }
           .Row (BodyRow.Prompt) .ColumnSpan (All<BodyCol>()) .FillExpandHorizontal () .CenterVertical () .Margin (fieldNameMargin) .TextCenterHorizontal () // Layout line

規則に従うことで、C# マークアップをすばやく読み取り、ビュー コンテンツが UI 内のどこにあるかを示すメンタル マップを作成できます。

Grid の行と列

列挙は、数値を使用する代わりに、行と列を定義 Grid するために使用できます。 これにより、行または列を追加または削除するときに番号を付け直す必要がないという利点があります。

重要

列挙を Grid 使用して行と列を定義するには、次 using のディレクティブが必要です。 using static Xamarin.CommunityToolkit.Markup.GridRowsColumns;

次のコードは、列挙型を使用して行と列を定義および使用 Grid する方法の例を示しています。

using Xamarin.Forms;
using Xamarin.CommunityToolkit.Markup;
using Xamarin.CommunityToolkit.Markup.LeftToRight;
using static Xamarin.CommunityToolkit.Markup.GridRowsColumns;
// ...

enum BodyRow { Prompt, CodeHeader, CodeEntry, Button }
enum BodyCol { FieldLabel, FieldValidation }

View Build() => new Grid
{
    RowDefinitions = Rows.Define(
        (BodyRow.Prompt    , 170 ),
        (BodyRow.CodeHeader, 75  ),
        (BodyRow.CodeEntry , Auto),
        (BodyRow.Button    , Auto)
    ),

    ColumnDefinitions = Columns.Define(
        (BodyCol.FieldLabel     , Stars(0.5)),
        (BodyCol.FieldValidation, Star)
    ),

    Children =
    {
        new Label { LineBreakMode = LineBreakMode.WordWrap } .FontSize (15) .Bold ()
                   .Row (BodyRow.Prompt) .ColumnSpan (All<BodyCol>()) .FillExpandHorizontal () .CenterVertical () .Margin (fieldNameMargin) .TextCenterHorizontal ()
                   .Bind (nameof(vm.RegistrationPrompt)),

        new Label { Text = "Registration code" } .Bold ()
                   .Row (BodyRow.CodeHeader) .Column(BodyCol.FieldLabel) .Bottom () .Margin (fieldNameMargin),

        new Label { } .Italic ()
                   .Row (BodyRow.CodeHeader) .Column (BodyCol.FieldValidation) .Right () .Bottom () .Margin (fieldNameMargin)
                   .Bind (nameof(vm.RegistrationCodeValidationMessage)),

        new Entry { Placeholder = "E.g. 123456", Keyboard = Keyboard.Numeric, BackgroundColor = Color.AliceBlue, TextColor = Color.Black } .FontSize (15)
                   .Row (BodyRow.CodeEntry) .ColumnSpan (All<BodyCol>()) .Margin (fieldMargin) .Height (44)
                   .Bind (nameof(vm.RegistrationCode), BindingMode.TwoWay),

        new Button { Text = "Verify" } .Style (FilledButton)
                    .Row (BodyRow.Button) .ColumnSpan (All<BodyCol>()) .FillExpandHorizontal () .Margin (PageMarginSize)
                    .Bind (Button.IsVisibleProperty, nameof(vm.CanVerifyRegistrationCode))
                    .Bind (nameof(vm.VerifyRegistrationCodeCommand)),
    }
};

さらに、列挙を使用せずに行と列を簡潔に定義できます。

new Grid
{
    RowDefinitions = Rows.Define (Auto, Star, 20),
    ColumnDefinitions = Columns.Define (Auto, Star, 20, 40)
    // ...
}

フォント

実装IFontElementするコントロールは、コントロール 、BoldItalicおよびFont拡張メソッドをFontSize呼び出して、コントロールによって表示されるテキストの外観を設定できます(例:

  • Button
  • DatePicker
  • Editor
  • Entry
  • Label
  • Picker
  • SearchBar
  • Span
  • TimePicker

効果

効果は、拡張メソッドを使用してコントロールに Effects アタッチできます。

new Button { Text = "Tap Me" }
            .Effects (new ButtonMixedCaps())

ロジックの統合

拡張メソッドを Invoke 使用して、C# マークアップでコードをインラインで実行できます。

new ListView { } .Invoke (l => l.ItemTapped += OnListViewItemTapped)

さらに、拡張メソッドを Assign 使用して、UI マークアップの外部 (UI ロジック ファイル内) からコントロールにアクセスできます。

new ListView { } .Assign (out MyListView)

スタイル

次の例は、C# マークアップを使用して暗黙的および明示的なスタイルを作成する方法を示しています。

using Xamarin.Forms;
using Xamarin.CommunityToolkit.Markup;

namespace CSharpForMarkupDemos
{
    public static class Styles
    {
        static Style<Button> buttons, filledButton;
        static Style<Label> labels;
        static Style<Span> link;

        #region Implicit styles

        public static ResourceDictionary Implicit => new ResourceDictionary { Buttons, Labels };

        public static Style<Button> Buttons => buttons ?? (buttons = new Style<Button>(
            (Button.HeightRequestProperty, 44),
            (Button.FontSizeProperty, 13),
            (Button.HorizontalOptionsProperty, LayoutOptions.Center),
            (Button.VerticalOptionsProperty, LayoutOptions.Center)
        ));

        public static Style<Label> Labels => labels ?? (labels = new Style<Label>(
            (Label.FontSizeProperty, 13),
            (Label.TextColorProperty, Color.Black)
        ));

        #endregion Implicit styles

        #region Explicit styles

        public static Style<Button> FilledButton => filledButton ?? (filledButton = new Style<Button>(
            (Button.TextColorProperty, Color.White),
            (Button.BackgroundColorProperty, Color.FromHex("#1976D2")),
            (Button.CornerRadiusProperty, 5)
        )).BasedOn(Buttons);

        public static Style<Span> Link => link ?? (link = new Style<Span>(
            (Span.TextColorProperty, Color.Blue),
            (Span.TextDecorationsProperty, TextDecorations.Underline)
        ));

        #endregion Explicit styles
    }
}

暗黙的なスタイルは、アプリケーション リソース ディクショナリに読み込むことで使用できます。

public App()
{
    Resources = Styles.Implicit;
    // ...
}

明示的なスタイルは、拡張メソッドで Style 使用できます。

using static CSharpForMarkupExample.Styles;
// ...

new Button { Text = "Tap Me" } .Style (FilledButton),

Note

拡張メソッドにStyle加えて、拡張CanCascadeメソッドもありますApplyToDerivedTypesBasedOnAdd

または、独自のスタイル拡張メソッドを作成することもできます。

public static TButton Filled<TButton>(this TButton button) where TButton : Button
{
    button.Buttons(); // Equivalent to Style .BasedOn (Buttons)
    button.TextColor = Color.White;
    button.BackgroundColor = Color.Red;
    return button;
}

Filledその後、拡張メソッドを次のように使用できます。

new Button { Text = "Tap Me" } .Filled ()

プラットフォーム固有設定

拡張メソッドは Invoke 、プラットフォーム固有の適用に使用できます。 ただし、あいまいさのエラーを回避するために、名前空間のディレクティブをXamarin.Forms.PlatformConfiguration.*Specific直接含usingめないでください。 代わりに、名前空間のエイリアスを作成し、エイリアスを使用してプラットフォーム固有を使用します。

using Xamarin.Forms;
using Xamarin.CommunityToolkit.Markup;
using PciOS = Xamarin.Forms.PlatformConfiguration.iOSSpecific;
// ...

new ListView { } .Invoke (l => PciOS.ListView.SetGroupHeaderStyle(l, PciOS.GroupHeaderStyle.Grouped))

さらに、特定のプラットフォーム固有のものを頻繁に使用する場合は、独自の拡張機能クラスで Fluent 拡張メソッドを作成できます。

public static T iOSGroupHeaderStyle<T>(this T listView, PciOS.GroupHeaderStyle style) where T : Forms.ListView
{
  PciOS.ListView.SetGroupHeaderStyle(listView, style);
  return listView;
}

その後、拡張メソッドを次のように使用できます。

new ListView { } .iOSGroupHeaderStyle(PciOS.GroupHeaderStyle.Grouped)

プラットフォーム固有の詳細については、「 Android プラットフォーム機能iOS プラットフォーム機能および Windows プラットフォーム機能」を参照してください。

プロパティとヘルパー メソッドの推奨される順序とグループ化は次のとおりです。

  • 目的: コントロールの目的を識別する値を持つ任意のプロパティまたはヘルパー メソッド (例: TextPlaceholder.Assign)。
  • その他: レイアウトやバインドではない、同じ行または複数行のすべてのプロパティまたはヘルパー メソッド。
  • レイアウト: レイアウトは、行と列、レイアウト オプション、余白、サイズ、パディング、およびコンテンツの配置の順に並べ替えられます。
  • バインド: データ バインディングは、1 行に 1 つのバインドされたプロパティを使用して、メソッド チェーンの最後に実行されます。 既定のバインド可能なプロパティがバインドされている場合は、メソッド チェーンの末尾に存在する必要があります。

次のコードは、次の規則の例を示しています。

new Button { Text = "Verify" /* purpose */ } .Style (FilledButton) // other
            .Row (BodyRow.Button) .ColumnSpan (All<BodyCol>()) .FillExpandHorizontal () .Margin (10) // layout
            .Bind (Button.IsVisibleProperty, nameof(vm.CanVerifyRegistrationCode)) // bind
            .Bind (nameof(vm.VerifyRegistrationCodeCommand)), // bind default

new Label { }
           .Assign (out animatedMessageLabel) // purpose
           .Invoke (label => label.SizeChanged += MessageLabel_SizeChanged) // other
           .Row (BodyRow.Message) .ColumnSpan (All<BodyCol>()) // layout
           .Bind (nameof(vm.Message)), // bind default

この規則を一貫して適用することで、C# マークアップをすばやくスキャンし、UI レイアウトのメンタル イメージを構築できます。

Xamarin Community Toolkit の追加機能

Xamarin Community Toolkit では、C# マークアップによって次のサポートが追加されます。

  • MultiBinding
  • MultiConverter
  • BindableLayout
  • RelativeLayout
  • DynamicResource

マルチバインディング ヘルパー

ヘルパーの新しいオーバーロードは Bindマルチバインディングのサポートを提供します。

型セーフなインライン コンバーターを使用して 2、3、または 4 個のバインドをサポートするオーバーロードがあります。

new Label { }
    .Bind (Label.TextProperty,
        new Binding (nameof(vm.Name)),
        new Binding (nameof(vm.Score)),
        ((string name, bool score) v) => $"{v.name} Score: { v.score }"
    )

すべてのバインディングの値は、型セーフ メンバーと共に ValueTuple 渡されます。

型セーフ なコンバーター パラメーターを渡すこともできます。

new Label { }
    .Bind (Label.TextProperty,
        new Binding (nameof(vm.Name)),
        new Binding (nameof(vm.Score)),
        ((string name, int Score) v, bool winner) => $"{v.name} Score: { v.Score } Winner: { winner }",
        converterParameter: true
    )

ここでは bool winner 、次の値を取得します converterParameter

双方向変換はインラインで指定できます。

new Entry { }
    .Bind(Entry.TextProperty,
        new Binding (nameof(vm.Emoticon)),
        new Binding (nameof(vm.Repeat)),
        ((char emoticon, int repeat) v) => new string(v.emoticon, v.repeat),
        (string emoticons) => (emoticons[0], emoticons.Length)
    );

関数では、 convertBack 関数で受け取ったのと同じもの ValueTupleconvert 返します。

複数値コンバーターを渡すことで、4 つ以上のバインドを指定できます。

new Label { }
    .Bind(Label.TextProperty,
        new List<BindingBase> {
            new Binding(nameof(vm.Name)),
            new Binding(nameof(vm.Score))
        },
        new FuncMultiConverter<string, bool>(
            (object[] values, bool winner) => $"{values[0]} Score: { values[1] } Winner: { winner }"
        )
    )

これは型セーフではありません。値を関数内 convert の型にキャストする必要があります。

クラスは FuncMultiConverter . IMultiValueConverter. 任意の数のバインディングに使用されるクラスは FuncMultiConverter<TDest, TParam>、変換先の型とコンバーターのパラメーター型のみを指定します。 バインド値は .. として object[]渡されます。

また、2、3、または 4 の値 (および必要に応じてコンバーター パラメーター) を受け取る型セーフなジェネリック オーバーロード FuncMultiConverter もあります。 これらのクラスは、型セーフ ValueTupleでバインド値を渡します。

バインド可能なレイアウト ヘルパー

EmptyViewTemplateItemsSourceItemTemplateおよびItemTemplateSelectorヘルパーはEmptyView、すべてのLayout<View>型でバインド可能なレイアウトのサポートを提供します

new StackLayout { }
    .ItemTemplate (() =>
        new Label { }
            .Bind (nameof(Item.Name))
        )
    .ItemsSource (vm.Items)

RelativeLayout ヘルパー

Childrenヘルパーを使用すると、制約付き子ビューを RelativeLayout.

通常のビューから制約付きビューを作成するために、4 つのヘルパー (および Constraints 2 つのConstrainオーバーロード) Unconstrainedが追加されています。 各オーバーロードは対応する *ConstrainedView クラスを返します。これにより、子ビューに制約を設定するための Fluent API が RelativeLayout 提供されます。

子ビューに対する制約は、次のように設定できます。

  • 単一の Bounds 式。
  • X、Y、Width、Height の式を区切ります。
  • X、Y、Width、Height のインスタンスを分離 Constraint します。 これらの各制約インスタンスには、次のオーバーロードがあります。
    • 定数。
    • 親に対する相対値。
    • ビューに対する相対値。

次のコードは、これらのヘルパーの使用例を示しています。

new RelativeLayout { } .Children (
    new Label { } // Bounds constrained
        .Assign (out Label child0)
        .Constrain(() => new Rectangle(30, 20, layout.Height / 2, layout.Height / 4)),

    new Label { } // Expressions constrained
        .Constrain() .X      (() => 30)
                     .Y      (() => 20)
                     .Width  (() => layout.Height / 2)
                     .Height (() => layout.Height / 4),

    new Label { } // Constraints constrained - parent relative
        .Constraints() .X      (30)
                       .Y      (20)
                       .Width  (parent => parent.Height / 5)
                       .Height (parent => parent.Height / 10),

    new Label { } // Constraints constrained - view relative
        .Constraints() .X      (child0, (layout, view) => view.Bounds.Right + 10)
                       .Y      (child0, (layout, view) => view.Y)
                       .Width  (child0, (layout, view) => view.Width)
                       .Height (child0, (layout, view) => view.Height),
) .Assign (out layout)

動的リソース ヘルパー

および DynamicResourcesRemoveDynamicResourcesヘルパーはDynamicResource、次の項目に動的リソースを設定するためのサポートをElement追加します。

new Label { }
    .DynamicResource (Label.TextProperty, "TextKey")

new Label { }
    .DynamicResources((Label.TextProperty     , "TextKey"),
                      (Label.TextColorProperty, "ColorKey"));