Share via


Xamarin Community Toolkit C# マークアップ

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

C# マークアップは、宣言型 Xamarin を構築するプロセスを簡略化するための fluent ヘルパー メソッドとクラスのセットです。C# でユーザー インターフェイスをFormsします。 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。

注意

C# マークアップのプレビュー バージョンは Xamarin で入手できます。実験機能として 4.6 から 4.8 をFormsします。

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

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

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

基本的な例

次の例は、C# で と を含む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オブジェクトとオブジェクトを含む オブジェクトをEntry作成Gridします。 には Label テキストが表示され、データは Entry viewmodel の RegistrationCode プロパティにバインドされます。 各子ビューは、 の特定の行に Grid表示されるように設定され、 Entry 内のすべての列 Gridにまたがっています。 さらに、 の 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 を構築するプロセスが簡略化されます。

注意

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

名前空間の使用

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

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

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

  • LTR のみ: も含めます using Xamarin.CommunityToolkit.Markup.LeftToRight;
  • RTL のみ: も含める using Xamarin.CommunityToolkit.Markup.RightToLeft;
  • LTR と RTL の両方: または RightToLeft 名前空間を含LeftToRightめないでください

行と列を操作 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)
);

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

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 プロパティは、および BindTapGesture 拡張メソッドをGestureElement使用して、 View および 型にBindClickGestureBindSwipeGestureバインドされたデータにすることができます。

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

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

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

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

ジェスチャ認識エンジンは であるため、 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のセット 、 RightTop および Bottomを提供します。

左右の拡張メソッドの正しいセットを使用できるようにし、プロセスでマークアップが設計されているフロー方向を明示的にするには、次の 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),

注意

拡張メソッドにStyle加えて、、および CanCascade 拡張メソッドもありますBasedOnApplyToDerivedTypesAdd

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

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 プラットフォーム機能」を参照してください。

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

  • 目的: コントロールの目的を識別する値を持つ任意のプロパティまたはヘルパー メソッド (、 などTextPlaceholderAssign)。
  • その他: レイアウトまたはバインドではないすべてのプロパティまたはヘルパー メソッド (同じ行または複数行)。
  • レイアウト: レイアウトは、行と列、レイアウト オプション、余白、サイズ、パディング、コンテンツの配置など、内側に並べ替えられます。
  • バインド: データ バインディングは、メソッド チェーンの末尾で実行され、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 します。 これらの各 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)

動的リソース ヘルパー

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

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

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