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