【发布时间】:2017-03-29 16:42:23
【问题描述】:
所以我正在为通用 Windows 平台进行开发。我正在从网站中提取图像作为 base64 字符串,并使用 byte[] imageBytes = Convert.FromBase64String(srcString); 将其转换为字节数组,然后使用以下代码将其转换为 BitmapImage:
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;
}
看起来这会正确地拉入我的图像,因为 BitmapImage 对象中图像的维度属性已正确填充。问题是我需要使用带有以下 XAML 代码的图像画笔将此图像对象用作 GridView 项模板的背景:
<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>
我正确设置了后台代码,因为如果我将本地 URI 输入到 Image 绑定变量中,那么一切都会完美无缺。但是,由于我制作的 BitmapImage 中的 URI 属性为空,我无法仅获取它的 URI 并将其用于绑定。将图像作为字节数组获取是我能够做到的唯一方法。有没有办法使用我通过字节流提取的这个图像并将其绑定到我的 XAML 代码?
谢谢, 肯尼
【问题讨论】:
-
它是否适用于
ImageSource="{Binding Image}"?您还应该向我们展示您的 Image 属性的声明。 -
谢谢克莱门斯!这确实有效!那么 Binding 是否比 x:Bind 具有更高的兼容性?
标签: c# xaml uwp win-universal-app windows-10-universal