Xamarin.Forms DataTemplateSelector の作成Creating a Xamarin.Forms DataTemplateSelector
サンプルのダウンロード
Download the sample
DataTemplateSelector を使用して、データバインド プロパティの値に基づいて、実行時に DataTemplate を選択できます。これにより、複数の DataTemplates を同じ種類のオブジェクトに適用し、特定のオブジェクトの外観をカスタマイズできます。この記事では、DataTemplateSelector を作成して使用する方法を示します。A DataTemplateSelector can be used to choose a DataTemplate at runtime based on the value of a data-bound property. This enables multiple DataTemplates to be applied to the same type of object, to customize the appearance of particular objects. This article demonstrates how to create and consume a DataTemplateSelector.
データ テンプレート セレクターによって、オブジェクトのコレクションにバインドされる ListView
などのシナリオが可能になります。この場合、ListView
内の各オブジェクトの外観は、特定の DataTemplate
を返すデータ テンプレート セレクターによって実行時に選択できます。A data template selector enables scenarios such as a ListView
binding to a collection of objects, where the appearance of each object in the ListView
can be chosen at runtime by the data template selector returning a particular DataTemplate
.
DataTemplateSelector の作成Creating a DataTemplateSelector
データ テンプレート セレクターを実装するには、DataTemplateSelector
から継承するクラスを作成します。A data template selector is implemented by creating a class that inherits from DataTemplateSelector
. 次のコード例に示すように、OnSelectTemplate
メソッドがオーバーライドされ、特定の DataTemplate
が返されます。The OnSelectTemplate
method is then overridden to return a particular DataTemplate
, as shown in the following code example:
public class PersonDataTemplateSelector : DataTemplateSelector
{
public DataTemplate ValidTemplate { get; set; }
public DataTemplate InvalidTemplate { get; set; }
protected override DataTemplate OnSelectTemplate (object item, BindableObject container)
{
return ((Person)item).DateOfBirth.Year >= 1980 ? ValidTemplate : InvalidTemplate;
}
}
OnSelectTemplate
メソッドからは、DateOfBirth
プロパティの値に基づいて適切なテンプレートが返されます。The OnSelectTemplate
method returns the appropriate template based on the value of the DateOfBirth
property. 返されるテンプレートは、PersonDataTemplateSelector
の使用時に設定される ValidTemplate
プロパティまたは InvalidTemplate
プロパティの値です。The template to return is the value of the ValidTemplate
property or the InvalidTemplate
property, which are set when consuming the PersonDataTemplateSelector
.
データ テンプレート セレクター クラスのインスタンスは、ListView.ItemTemplate
などの Xamarin.Forms コントロール プロパティに割り当てることができます。An instance of the data template selector class can then be assigned to Xamarin.Forms control properties such as ListView.ItemTemplate
. 有効なプロパティの一覧については、DataTemplate の作成に関するページを参照してください。For a list of valid properties, see Creating a DataTemplate.
制限事項Limitations
DataTemplateSelector
インスタンスには次の制限事項があります。DataTemplateSelector
instances have the following limitations:
- 複数回クエリが実行された場合、同じデータに対して
DataTemplateSelector
サブクラスからは常に同じテンプレートが返される必要があります。TheDataTemplateSelector
subclass must always return the same template for the same data if queried multiple times. DataTemplateSelector
サブクラスから別のDataTemplateSelector
サブクラスを返すことはできません。TheDataTemplateSelector
subclass must not return anotherDataTemplateSelector
subclass.- 呼び出しごとに、
DataTemplateSelector
サブクラスから新しいインスタンスのDataTemplate
を返すことはできません。TheDataTemplateSelector
subclass must not return new instances of aDataTemplate
on each call. 代わりに、同じインスタンスを返す必要があります。Instead, the same instance must be returned. そうしないと、メモリ リークが発生し、仮想化が無効になります。Failure to do so will create a memory leak and will disable virtualization. - Android では、
ListView
ごとに使用できるデータ テンプレートは 20 種類以下です。On Android, there can be no more than 20 different data templates perListView
.
XAML での DataTemplateSelector の使用Consuming a DataTemplateSelector in XAML
XAML で PersonDataTemplateSelector
をインスタンス化するには、次のコード例のようにリソースとして宣言します。In XAML, the PersonDataTemplateSelector
can be instantiated by declaring it as a resource, as shown in the following code example:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:Selector;assembly=Selector" x:Class="Selector.HomePage">
<ContentPage.Resources>
<ResourceDictionary>
<DataTemplate x:Key="validPersonTemplate">
<ViewCell>
...
</ViewCell>
</DataTemplate>
<DataTemplate x:Key="invalidPersonTemplate">
<ViewCell>
...
</ViewCell>
</DataTemplate>
<local:PersonDataTemplateSelector x:Key="personDataTemplateSelector"
ValidTemplate="{StaticResource validPersonTemplate}"
InvalidTemplate="{StaticResource invalidPersonTemplate}" />
</ResourceDictionary>
</ContentPage.Resources>
...
</ContentPage>
このページ レベルの ResourceDictionary
には、2 つの DataTemplate
インスタンスと 1 つの PersonDataTemplateSelector
インスタンスが定義されています。This page level ResourceDictionary
defines two DataTemplate
instances and a PersonDataTemplateSelector
instance. PersonDataTemplateSelector
インスタンスでは、StaticResource
マークアップ拡張を使用して、ValidTemplate
および InvalidTemplate
プロパティが適切な DataTemplate
インスタンスに設定されます。The PersonDataTemplateSelector
instance sets its ValidTemplate
and InvalidTemplate
properties to the appropriate DataTemplate
instances by using the StaticResource
markup extension. リソースはページの ResourceDictionary
に定義されていますが、コントロール レベルまたはアプリケーション レベルで定義することもできる点に注意してください。Note that while the resources are defined in the page's ResourceDictionary
, they could also be defined at the control level or application level.
PersonDataTemplateSelector
インスタンスを使用するには、次のコード例に示すように、ListView.ItemTemplate
プロパティに割り当てます。The PersonDataTemplateSelector
instance is consumed by assigning it to the ListView.ItemTemplate
property, as shown in the following code example:
<ListView x:Name="listView" ItemTemplate="{StaticResource personDataTemplateSelector}" />
実行時に、基となるコレクション内の項目ごとに、ListView
から PersonDataTemplateSelector.OnSelectTemplate
メソッドが呼び出されます。このとき、呼び出しでデータ オブジェクトが item
パラメーターとして渡されます。At runtime, the ListView
calls the PersonDataTemplateSelector.OnSelectTemplate
method for each of the items in the underlying collection, with the call passing the data object as the item
parameter. このメソッドから返された DataTemplate
はそのオブジェクトに適用されます。The DataTemplate
that is returned by the method is then applied to that object.
次のスクリーンショットは、ListView
によって、基となるコレクション内の各オブジェクトに対して PersonDataTemplateSelector
が適用された結果を示しています。The following screenshots show the result of the ListView
applying the PersonDataTemplateSelector
to each object in the underlying collection:
DateOfBirth
プロパティ値が 1980 以上のすべての Person
オブジェクトは緑色で表示され、その他のオブジェクトは赤色で表示されます。Any Person
object that has a DateOfBirth
property value greater than or equal to 1980 is displayed in green, with the remaining objects being displayed in red.
C# での DataTemplateSelector の使用Consuming a DataTemplateSelector in C#
次のコード例に示すように、C# では、PersonDataTemplateSelector
をインスタンス化して ListView.ItemTemplate
プロパティに割り当てることができます。In C#, the PersonDataTemplateSelector
can be instantiated and assigned to the ListView.ItemTemplate
property, as shown in the following code example:
public class HomePageCS : ContentPage
{
DataTemplate validTemplate;
DataTemplate invalidTemplate;
public HomePageCS ()
{
...
SetupDataTemplates ();
var listView = new ListView {
ItemsSource = people,
ItemTemplate = new PersonDataTemplateSelector {
ValidTemplate = validTemplate,
InvalidTemplate = invalidTemplate }
};
Content = new StackLayout {
Margin = new Thickness (20),
Children = {
...
listView
}
};
}
...
}
PersonDataTemplateSelector
インスタンスでは、SetupDataTemplates
メソッドで作成された適切な DataTemplate
インスタンスに ValidTemplate
および InvalidTemplate
プロパティが設定されます。The PersonDataTemplateSelector
instance sets its ValidTemplate
and InvalidTemplate
properties to the appropriate DataTemplate
instances created by the SetupDataTemplates
method. 実行時に、基となるコレクション内の項目ごとに、ListView
から PersonDataTemplateSelector.OnSelectTemplate
メソッドが呼び出されます。このとき、呼び出しでデータ オブジェクトが item
パラメーターとして渡されます。At runtime, the ListView
calls the PersonDataTemplateSelector.OnSelectTemplate
method for each of the items in the underlying collection, with the call passing the data object as the item
parameter. このメソッドから返された DataTemplate
はそのオブジェクトに適用されます。The DataTemplate
that is returned by the method is then applied to that object.
まとめSummary
この記事では、DataTemplateSelector
を作成して使用する方法について説明しました。This article has demonstrated how to create and consume a DataTemplateSelector
. DataTemplateSelector
を使用すると、データバインド プロパティの値に基づいて実行時に DataTemplate
を選択できます。A DataTemplateSelector
can be used to choose a DataTemplate
at runtime based on the value of a data-bound property. これにより、複数の DataTemplate
インスタンスを同じ種類のオブジェクトに適用し、特定のオブジェクトの外観をカスタマイズできます。This enables multiple DataTemplate
instances to be applied to the same type of object, to customize the appearance of particular objects.