Xamarin.Forms Guides | Samples

Xamarin.Forms.DataTemplateSelector Class

Selects DataTemplate objects by data type and container.

See Also: DataTemplateSelector

Syntax

public abstract class DataTemplateSelector : DataTemplate

Remarks

Application developers override the DataTemplateSelector.OnSelectTemplate method to return a unique DataTemplate for a data type and parent container combination. Additionally, because the same exact template instance must be returned for a given piece of data across successive calls to DataTemplateSelector.SelectTemplate, developers should create and store these DataTemplate in their constructor overrides.

Note: Developers should note the following items:
  • OnSelectTemplate must not return another DataTemplateSelector, and
  • The Android platform is limited to 20 templates per list view.
The following example shows a basic use:

c# Example

class MyDataTemplateSelector : DataTemplateSelector
{
    public MyDataTemplateSelector ()
    {
        // Retain instances
        this.templateOne = new DataTemplate (typeof (ViewA));
        this.templateTwo = new DataTemplate (typeof (ViewB));
    }

    protected override DataTemplate OnSelectTemplate (object item, BindableObject container)
    {
        if (item is double)
            return this.templateOne;
        return this.templateTwo;
    }

    private readonly DataTemplate templateOne;
    private readonly DataTemplate templateTwo;
}

Requirements

Namespace: Xamarin.Forms
Assembly: Xamarin.Forms.Core (in Xamarin.Forms.Core.dll)
Assembly Versions: 2.0.0.0

The members of Xamarin.Forms.DataTemplateSelector are listed below.

See Also: DataTemplate

Protected Constructors

Creates a new DataTemplateSelector with default values.

Public Methods

SelectTemplate(Object, BindableObject) : DataTemplate
When overriden by developers in a derived class, returns a DataTemplate for item.

Protected Methods