[英]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 圖標列表。 硬編碼的十六進制值有效
 
Unicode 值只是呈現為
"\uf236 \uf1eb"
如何獲取要呈現為完整列表的圖標列表?
根據你的說法
其中 Features 是一個逗號分隔的 Fontawesome 圖標列表。 硬編碼的十六進制值有效
我將假設Features
的以下代碼解釋,您將需要:
List<string>
屬性,以便綁定到 UI。string Features = ", , , ";
public List<string> IconsList { get; set; }
public MainPage()
{
BindingContext = this;
IconsList = Features.Trim().Split(',').Select(x => x.Trim()).ToList();
InitializeComponent();
}
在您的 UI 中,您可以使用BindableLayout
、 CollectionView
或ListView
來綁定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;
}
}
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.