2

我希望不是将图像源绑定到Image我的绑定源的属性,而是指向一个远程获取图像的异步方法。我需要能够传入两个参数。

图像提取

class ConnectImage
{
    public static async Task<BitmapImage> GetImageAsync(Uri uri, String sid)
    {
        HttpClient httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("Authorization", "OAuth " + sid); 

        HttpResponseMessage response = await httpClient.GetAsync(uri);

        BitmapImage bmp = new BitmapImage();
        byte[] byteArray = await response.Content.ReadAsByteArrayAsync();

        InMemoryRandomAccessStream ras = new InMemoryRandomAccessStream();
        DataWriter writer = new DataWriter(ras.GetOutputStreamAt(0));
        writer.WriteBytes(byteArray);
        BitmapImage image = new BitmapImage();
        image.SetSource(ras);
        return image;
    }
}

列表显示

<ListView
        x:Name="itemListView"
        Grid.Row="1"
        ItemsSource="{Binding Source={StaticResource itemsViewSource}}"
        IsSwipeEnabled="False"
        ItemTemplate="{StaticResource FeedItemTemplate}"/>

饲料项目模板

<DataTemplate x:Key="FeedItemTemplate">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border Width="110" Height="110">
            <Image Source="{Binding Image}" Stretch="UniformToFill" />
        </Border>
    </Grid>
</DataTemplate>
4

1 回答 1

2

属性不能是async,因此您需要一个async在完成时设置属性的初始化。

在您的虚拟机中:

public BitmapImage Image { get; private set; }

public async Task Load()
{
  Image = await ConnectImage.GetImageAsync(...);
  ... // other asynchronously-loaded properties
}

然后让你的页面Loaded事件加载你的虚拟机:

public async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
  await vm.Load();
}

您的页面最初将Image设置为显示null,并且当加载图像时,它将显示在页面上。

于 2012-11-27T13:51:11.740 回答