如何将嵌入式图像与由 C# 代码后面的字符串指定的变量 ImageSource 绑定?

How to Bind Embedded Image with variable ImageSource that is specified by a string in C# code behind?

我想在 Xamarin Forms 中显示变量图像。我想在 XAML 中绑定 ImageSource。我已尝试使用文档中提到的 IMarkupExtension,但限制是我需要在 XAML 本身中指定整个路径。我想绑定 ImageSource 可以在需要时改变。我不想在 XAML.

中指定整个路径

这是我的工作 XAML 代码:

<Image Source="{local:ImageResource MyProject.Images.photo.jpg}" />

这里是XAML无效的代码:

<Image Source="{Binding imgSource StringFormat=local:ImageResource `MyProject.Images.{0}`" />

Microsoft 没有在官方文档的 XAML 中提供有关绑定变量 ImageSource 的信息。您需要 IValueConverterImageSource.FromResource()string 转换为 ImageSource 以绑定变量 Image.

在图像属性中将图像设置为 Build: EmbeddedResource

这是转换的扩展

public class EmbeddedToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is string fileName && parameter is string assemblyName)
        {
            try
            {
                Debug.WriteLine("Assembly Name: " + assemblyName);  // Just for reference, remove in Release mode
                var imageSource = ImageSource.FromResource(assemblyName + "." + fileName, typeof(EmbeddedToImageSourceConverter).GetTypeInfo().Assembly);
                return imageSource;
            }
            catch (Exception)
            {
                return value;
            }
        }
        else
            return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

在你的XAML

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             ...
             xmlns:extensions="clr-namespace:MyProject.Extensions">

    <ContentPage.Resources>
        <extensions:EmbeddedToImageSourceConverter x:Key="imageConverter" />
    </ContentPage.Resources>

    <ContentPage.Content>
        <StackLayout>
            <Image Source="{Binding IconSource, Converter={StaticResource imageConverter}, ConverterParameter='MyProject.Resources.Images'}"
                           HeightRequest="40" WidthRequest="40" Aspect="AspectFit" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

在 C# 代码后面 (xaml.cs)

public string IconSource { get { return "photo.png"; } set { } }

public MainPage()
{
    InitializeComponent();
    BindingContext = this;
}

您可以将 BindingContext 设置为您的 ViewModel 并实施 INotifyPropertyChanged,这将使用 C# 代码同步您 XAML 中的 IconSource 图像。

注意 我在 StaticResource imageConverter 的开始大括号附近的第 <Image Source="{Binding IconSource, Converter={StaticResource imageConverter}, ... 行获得 Intellisense error/warning。错误显示 No DataContext found for Binding "。但是代码 working 很好。任何人都可以解释错误的原因或改进欢迎使用示例代码来消除错误。如果找到原因,请编辑答案。