Xamarin.Forms中如何为嵌入式图片资源实现绑定功能?
问题原因
- 你自定义的
EmbeddedImage标记扩展仅实现了IMarkupExtension接口,ResourceId是普通CLR属性,未实现可绑定属性(BindableProperty),XAML不支持在这类属性上直接嵌套Binding表达式赋值,这是触发XFC0009报错的直接原因。 - MainPage中定义的
One是字段,不是公共属性,XAML绑定仅支持绑定属性,不支持字段,即便扩展支持绑定也无法正常取值。
可行解决方案
推荐使用值转换器实现需求,改动量小且符合Xamarin.Forms绑定规范:
步骤1:创建资源ID转ImageSource的值转换器
using System; using Xamarin.Forms; namespace MyNameSpace { public class ResourceIdToImageSourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is string resourceId && !string.IsNullOrWhiteSpace(resourceId)) { return ImageSource.FromResource(resourceId); } return null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
步骤2:修改MainPage的One为可通知属性
将原本的字段改为支持属性变更通知的公共属性,满足动态修改的需求:
namespace MyNameSpace { public partial class MainPage : ContentPage, INotifyPropertyChanged { public new event PropertyChangedEventHandler PropertyChanged; private string _one = "MyNameSpace.Images.Blue.jpg"; public string One { get => _one; set { _one = value; OnPropertyChanged(); } } public MainPage() { InitializeComponent(); } protected override void OnPropertyChanged ([CallerMemberName] string name = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name)); } } }
步骤3:修改XAML代码
注册转换器资源,绑定Source时使用转换器做类型转换:
<?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyNameSpace" x:Class="MyNameSpace.MainPage" x:Name = "Main"> <ContentPage.Resources> <ResourceDictionary> <local:ResourceIdToImageSourceConverter x:Key="ResToImgConverter" /> </ResourceDictionary> </ContentPage.Resources> <StackLayout BindingContext="{x:Reference Main}"> <Image Source="{Binding One, Converter={StaticResource ResToImgConverter}}"/> </StackLayout> </ContentPage>
注意事项
确保图片文件的生成操作设置为嵌入式资源,否则无法通过资源ID加载到图片。
内容的提问来源于stack exchange,提问作者Luca Hafer
相关产品推荐
相关产品推荐

