Reputation: 174
So I am developing for the Universal Windows Platform. I am pulling in an image from a website as a base64 string and converting it to a byte array using byte[] imageBytes = Convert.FromBase64String(srcString);
the converting that to a BitmapImage with the following code:
public async static Task<BitmapImage> ImageFromBytes(Byte[] bytes)
{
BitmapImage image = new BitmapImage();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(bytes.AsBuffer());
stream.Seek(0);
await image.SetSourceAsync(stream);
}
return image;
}
It appears like this pulls in my image correctly as dimension properties of the image in the BitmapImage object are populated correctly. The problem is that I need to use this image object as the background of a GridView Item template using an image brush with the following XAML code:
<GridView.ItemTemplate>
<DataTemplate x:DataType="models:data" >
<StackPanel
Orientation="Horizontal"
HorizontalAlignment="Center"
Width="190"
Height="270"
BorderThickness="1" BorderBrush="DarkBlue"
>
<StackPanel.Background>
<ImageBrush Stretch="Fill" ImageSource="{x:Bind Image}"/>
</StackPanel.Background>
<StackPanel HorizontalAlignment="Center" Padding="5" >
<StackPanel Orientation="Horizontal" >
<TextBlock Text="Title:" FontWeight="Bold" />
<TextBlock Name="Block" Margin="5,0,0,0"
Text="{x:Bind Title}" />
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
I have the back code set up correctly because if I feed a local URI in to the Image bound variable then everything works flawlessly. But, since the URI property in the BitmapImage I made is null, I am unable to just get the URI for it and use that for the binding. Getting the image as a byte array is the only way I am able to do it. Is there a way to use this image I pulled in with a byte stream and bind it to my XAML code?
Thanks, Kenny
Upvotes: 0
Views: 1070
Reputation: 128013
Use
ImageSource="{Binding Image}"
instead of
ImageSource="{x:Bind Image}"
While x:Bind
requires an exact type match, Binding
takes advantage of built-in conversion from several source types (e.g. string
, Uri
, byte[]
) to ImageSource
.
Upvotes: 2
Reputation: 174
Changed the ImageSource
ImageSource="{Binding Image}"
Much thanks to Clemens!
Upvotes: 0