[英]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.