-1

I have a Xamarin forms app where I exhibit the result from different sensors all in one ListView. Every sensor populates a 'DataTemplate' ViewCell where I show the name, location and others and, in the central grid the values.

The point is that the visualization for those values should be different from each sensor (imagine I want a moving arrow for the wind, a growing blue box for the collected water, a number for the temperature, and so on)

Is it possible to return a custom UIElement, or a Grid or something from a IValueConverter and be able to do this task ? If not, what would you recommend ?

PS: I think that, what I want to do, is done via ContentPresenter. but .. I cannot find proper details on how to achieve it.

javirs
  • 1,049
  • 26
  • 52

1 Answers1

2

Sounds like DataTemplateSelector should solve your issue:

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.

Official docs: Creating a Xamarin.Forms DataTemplateSelector

Creating a DataTemplateSelector:

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;
  }
}

Consuming a DataTemplateSelector in XAML:

<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>

<ListView x:Name="listView" ItemTemplate="{StaticResource personDataTemplateSelector}" />
EvZ
  • 11,889
  • 4
  • 38
  • 76