Xamarin中如何拼接IconCode字符串实现Material图标动态调用
C#后台代码实现方案
你原写法无法生效的原因是:\u开头的Unicode转义序列属于C#编译期语法,运行时通过字符串插值拼接不会被识别为Unicode转义,只会被当成普通字符处理。
正确写法如下:
string iconCode = "e87e"; // 将十六进制编码转换为对应Unicode字符 int unicodeVal = Convert.ToInt32(iconCode, 16); Label label = new Label { FontFamily = "IconMaterial", Text = char.ConvertFromUtf32(unicodeVal) };
也可以简化为Text = ((char)unicodeVal).ToString(),效果完全一致。
XAML实现方案
静态使用场景
如果图标编码固定,直接用XML字符实体语法即可:
<Label FontFamily="IconMaterial" Text="" />
动态绑定场景
如果需要动态绑定编码值,配合IValueConverter实现:
- 首先实现转换器类
using System; using System.Globalization; using Xamarin.Forms; public class HexToIconConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is not string hexCode || string.IsNullOrWhiteSpace(hexCode)) return string.Empty; try { int unicode = Convert.ToInt32(hexCode, 16); return char.ConvertFromUtf32(unicode); } catch { return string.Empty; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
- 在XAML中注册转换器资源
<ContentPage.Resources> <local:HexToIconConverter x:Key="HexToIconConverter" /> </ContentPage.Resources>
- 绑定使用
<!-- 绑定ViewModel中的IconCode字符串属性即可动态切换图标 --> <Label FontFamily="IconMaterial" Text="{Binding IconCode, Converter={StaticResource HexToIconConverter}}" />
内容的提问来源于stack exchange,提问作者Beny
相关产品推荐
相关产品推荐

