【发布时间】:2021-01-03 09:56:41
【问题描述】:
我为ImageSource 创建了一个IMarkupExtension,它从指定的字体中获取指定的符号,并以指定的颜色和指定的高度显示它。大多数时候,图标名称是静态的,我直接写入 XAML。但有时有些事物的列表具有确定应使用哪个图标的属性。对于这种情况,图标名称必须是可绑定的。
这是(或多或少)我的FontImageExtension 的当前状态:
[ContentProperty(nameof(IconName))]
public class FontImageExtension : IMarkupExtension<ImageSource>
{
private readonly IconFontService iconFontService;
[TypeConverter(typeof(FontSizeConverter))]
public double Size { get; set; } = 30d;
public string IconName { get; set; }
public Color Color { get; set; }
public string FontFamily { get; set; }
public FontImageExtension()
{
iconFontService = SomeKindOfContainer.Resolve<IconFontService>();
}
public ImageSource ProvideValue(IServiceProvider serviceProvider)
{
if (string.IsNullOrEmpty(IconName))
return null;
IconFont iconFont = iconFontService.GetIconFont();
if (iconFont == null)
return null;
string glyphCode = iconFont.GetGlyphCode(IconName);
if (string.IsNullOrEmpty(glyphCode))
return null;
FontImageSource fontImageSource = new FontImageSource()
{
FontFamily = iconFont.GetPlatformLocation(),
Glyph = glyphCode,
Color = this.Color,
Size = this.Size,
};
return fontImageSource;
}
object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
{
return ProvideValue(serviceProvider);
}
}
大多数时候我在 XAML 中这样使用它(已经完美运行):
<Image Source="{m:FontImage SomeIcon, Color=Black, Size=48}"/>
但是对于动态 UI(例如列表或其他东西),我需要这样:
<CollectionView ItemsSource={Binding SomeCollection}">
<CollectionView.ItemTemplate>
<StackLayout>
<Image Source="{m:FontImage IconName={Binding ItemIcon}, Color=Black, Size=48}"/>
<Label Text="{Binding ItemText}"/>
</StackLayout>
</CollectionView.ItemTemplate>
</CollectionView>
我怎样才能做到这一点?
【问题讨论】:
标签: c# xaml xamarin binding markup-extensions