xamarin.forms - 从 URL 加载图像并带有引用标题
问题描述
我需要从我的 CDN 下载静态图像并将它们显示在我的 Xamarin.Forms 视图中。我是 Xamarin 的新手,我很难弄清楚如何从 HTTP 请求中提取的字节数组中加载图像。
我的视图中有以下 XAML:
<ListView ItemsSource="{Binding Images}">
<ListView.ItemTemplate>
<DataTemplate>
<ImageCell ImageSource="{Binding .}">
</ImageCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在我后面的代码中,我正在获取图像并尝试绑定到ImageSource
实例集合。
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
public ObservableCollection<ImageSource> Images { get; set; } = new ObservableCollection<ImageSource>();
protected override async void OnAppearing()
{
base.OnAppearing();
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Referer", "https://foo.bar/");
var response = await client.GetAsync("https://foo.bar/library/5.jpg");
byte[] image = await response.Content.ReadAsByteArrayAsync();
var imageSource = ImageSource.FromStream(() => new MemoryStream(image));
this.Images.Add(imageSource);
}
}
当我这样做时,StackLayout 中的图像是空的。我知道我可以改为绑定到一个 URL,ImageSource 可以为我下载它,但我需要传递一个Referrer
Header。我无论如何都看不到强制 XAML视图允许自定义标头,如果我在后面的代码中Image
实例化一个实例,我也看不到这样做的方法。ImageSource
当我阅读它的文档时ImageSource
,听起来它只支持 URI、文件、流和应用程序资源来加载图像。因为我有一个字节数组,所以我将它包装在 a 中MemoryStream
并调用ImageSource.FromStream
. 虽然应用程序运行时没有加载任何内容 -ImageCell
是空的。
我知道图像已下载。我将其转换byte[]
为 Base64 字符串,然后将其放入Base64 to Image Decoder。图像加载没有问题,所以我知道它正在正确下载。我不明白的是为什么我不能让图像在ImageSource
.
我也尝试只使用普通Image
控件并遇到同样的问题。
<ScrollView>
<ContentView>
<StackLayout BindableLayout.ItemsSource="{Binding Images}" Orientation="Horizontal">
<BindableLayout.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}"></Image>
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
</ContentView>
</ScrollView>
我在这里做错了什么,还是从互联网上动态下载带有特殊标题的图像,这是我在 Xamarin.Forms 中无法做到的?
解决方案
尝试添加 this.BindingContext = this;
页面构造函数。
public MainPage()
{
InitializeComponent();
this.BindingContext = this;
}
推荐阅读
- net-snmp - 网络 SNMP:snmpbulkget - genError 失败
- npm - 当脚本返回 1 时,如何将 gitlab 作业设置为失败?
- c - 同一指针的值不同,具体取决于我调用它的位置
- javascript - 类型“字符串”没有调用签名
- c# - 从 tnsnames.ora 获取数据库服务器 IP
- python - 如何获取调用另一个文件函数的 Python 文件的名称?
- sparql - 如何在 rdflib 中使用 SPARQL 命令 INSERT?(不是插入数据)
- c++ - 如果我将 2 个函数放在同一个头文件中,程序将无法编译。如果我将函数放在单独的头文件中,我将编译
- react-native - 如何解决 React Native onPress 事件不起作用
- parsing - 从 Antlr 开始时遇到问题