将图像绑定到URL Xamarin Forms XAML

5

我遇到了在Xamarin Forms中使用UriImageSource绑定图像的问题。

我已经实现了FlowListView,它呈现了一个类似网格的文本列表,但与每个产品相关联的图像没有出现。

还有其他人遇到过这个问题吗?或者知道如何解决吗?

XAML:

<flv:FlowListView 
    Grid.Row="1" 
    x:Name="flvListView" 
    SeparatorVisibility="None" 
    HasUnevenRows="true" 
    FlowColumnMinWidth="110">
    <flv:FlowListView.FlowColumnTemplate>
        <DataTemplate>
            <Grid Padding="3">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Image HeightRequest="100" >
                    <Image.Source>
                        <UriImageSource Uri="{Binding ProductImage}" />
                    </Image.Source>
                </Image>
                <Label 
                    x:Name="Label" 
                    HorizontalOptions="Fill" 
                    HorizontalTextAlignment="Center" 
                    VerticalOptions="End" 
                    BackgroundColor="Silver"
                    Opacity="0.5" Text="{Binding ProductName}"/>
            </Grid>
        </DataTemplate>
    </flv:FlowListView.FlowColumnTemplate>
</flv:FlowListView>

视图模型:

public class vmProduct
{
    public vmProduct() { }
    /* removed other properties, constructors etc */
    public UriImageSource ProductImage { get; set; }
    public string ProductName { get; set; }
}

当vmProduct被初始化时
this.Products.Add(new vmProduct
{
    ProductName = "Test",
    ProductImage = new UriImageSource
    {
        Uri = new Uri("https://upload.wikimedia.org/wikipedia/en/5/5f/Original_Doge_meme.jpg")
    }
});

在上面的例子中,“Test”将会出现,但是图片不会显示。

1
@jzeferino 收到,谢谢! - Dan M
2个回答

11

由于您正在将 UriImageSource 绑定到 Uri,因此您的 ViewModel 属性必须也是一个 Uri。

public UriImageSource ProductImage { get; set; } 更改为 public Uri ProductImage { get; set; }


1

我曾经遇到过同样的问题,虽然我不知道现在是否有所改变,但我发现可以直接将图像源绑定到以下位置:

<Image HeightRequest="200" Source="{Binding ProductImage}"/>

然后在代码后台,您可以使用一个变量,并让C#进行适当的转换:

   public ImageSource ProductImage {
        get {
            var source =  new Uri("http://myurl.com/one.jpg");
            return source;
        }
    }

我喜欢的是,如果您想让您的代码与资源中的图像配合使用,我们只需更改源行,如下所示:
    public ImageSource ProductImage {
        get {
            var source = "resource_image.png"
            return source;
        }
    }

需要注意的一点是,截至2018年,在MacOS上使用Xamarin加载TLS(https URL)图像存在问题,因此建议使用http或在Windows上构建。


你能详细说明一下你最后一段的意思吗?因为我好像遇到了这个问题,就像这里描述的一样:https://stackoverflow.com/questions/58312494/image-not-appearing-on-mac-images-does-appear-on-pc +1。 - w0051977
在我从芝加哥的一个合同项目中工作时,我们意识到了一些事情。团队中的大多数成员都感到惊讶,同样的代码可以在他们的Windows机器上运行,但却总是在Mac上失败。后来发现这似乎是某种错误。这是在2018年的情况,所以更新版本的Xamarin可能已经纠正了这个错误。 - Atif
@w0051977 我不认为这是同样的问题,因为您没有使用https/TLS。个人建议您主要在Windows上坚持使用Xamarin,或者使用另一个框架。也许可以在Mac上运行Windows虚拟机? - Atif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接