Home > Mobile >  Binding Fontawesome icons to a dynamic list in Xamarin
Binding Fontawesome icons to a dynamic list in Xamarin

Time:01-19

I have a list of icons that need to be dynamically bound to a Xamarin page.

The Xaml is:

<Label
    Grid.Row="2"
    Grid.ColumnSpan="4"
    HorizontalOptions="Start"
    Style="{StaticResource IconLabelStyle}"
    Text="{Binding Features}"/>

where Features is a comma separated list of Fontawesome icons. Hardcoded hex values work

&#xf236;  &#xf1eb;

Unicode values just render as

"\uf236  \uf1eb"

How can I get the list of icons to render as a complete list?

CodePudding user response:

Based on your statement

where Features is a comma separated list of Fontawesome icons. Hardcoded hex values work

I will assume the below code interpretation of Features, you will need to:

  • Split each icon's code and remove extra spaces.
  • Assign divided icon's codes to a List<string> property, in order to bind to the UI.
string Features = "&#xf236;, &#xf1eb, &#xf236;, &#xf1eb";
public List<string> IconsList { get; set; }

    public MainPage()
    {
        BindingContext = this;
        IconsList = Features.Trim().Split(',').Select(x => x.Trim()).ToList();
        InitializeComponent();
    }

In your UI you can use bind IconsList property using BindableLayout, CollectionView or ListView:

<StackLayout BindableLayout.ItemsSource="{Binding IconsList}" Orientation="Horizontal">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding .}"/>
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</StackLayout>

Note

If you are adding/removing (not only during first appearing of the page), then you may need to change the type List<string> to ObservableCollection<string>.

Docs

  •  Tags:  
  • Related