如何绑定到异步图像源

时间:2012-11-27 04:54:49

标签: c# windows-8 windows-store-apps

我希望代替将图像源绑定到绑定源的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

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

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>

1 个答案:

答案 0 :(得分:2)

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

在你的虚拟机中:

public BitmapImage Image { get; private set; }

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

然后让您的页面Loaded事件加载您的VM:

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

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