簡體   English   中英

將 Fontawesome 圖標綁定到 Xamarin 中的動態列表

[英]Binding Fontawesome icons to a dynamic list in Xamarin

我有一個需要動態綁定到 Xamarin 頁面的圖標列表。

Xaml 是:

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

其中 Features 是一個逗號分隔的 Fontawesome 圖標列表。 硬編碼的十六進制值有效

&#xf236;  &#xf1eb;

Unicode 值只是呈現為

"\uf236  \uf1eb"

如何獲取要呈現為完整列表的圖標列表?

根據你的說法

其中 Features 是一個逗號分隔的 Fontawesome 圖標列表。 硬編碼的十六進制值有效

我將假設Features的以下代碼解釋,您將需要:

  • 拆分每個圖標的代碼並刪除多余的空格。
  • 將分割圖標的代碼分配給List<string>屬性,以便綁定到 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();
    }

在您的 UI 中,您可以使用BindableLayoutCollectionViewListView來綁定IconsList屬性:

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

筆記

如果您正在添加/刪除(不僅在頁面首次出現期間),那么您可能需要將類型List<string>更改為ObservableCollection<string>

文檔

您也可以使用單個Label來實現它。

自定義標簽

public class MyLabel : Label
{
    public static readonly BindableProperty MyTextProperty =
      BindableProperty.Create("MyText", typeof(string), typeof(MyLabel), null, propertyChanged: BindingPropertyChangedDelegate);

    public string MyText
    {
        get { return (string)GetValue(MyTextProperty); }
        set { SetValue(MyTextProperty, value); }
    }

    static void BindingPropertyChangedDelegate(BindableObject bindable, object oldValue, object newValue)
    {
        if (newValue == null) return;

        var IconsList = ((string)newValue).Trim().Split(',').Select(x => x.Trim()).ToList();

        if (IconsList == null || IconsList.Count == 0) return;

        FormattedString text = new FormattedString();

        foreach(var str in IconsList)
        {
            text.Spans.Add(new Span { Text = "  " });
            text.Spans.Add(new Span { Text = str, FontFamily = "FontAwesomeSolid"});
        }

        ((Label)bindable).FormattedText = text;
    }
}

Xaml 用法

xmlns:local="clr-namespace:MyForms.View"

<local:MyLabel MyText="{Binding Features}"/>

背后的代碼

Features = "\uf164,\uf140,\uf236,\uf1eb,\uf5e1,\uf14a,\uf14b,\uf520,\uf14d,\uf14e,\uf578,\uf15c";
this.BindingContext = this;

在此處輸入圖像描述

參考

https://devblogs.microsoft.com/xamarin/embedded-fonts-xamarin-forms/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM