【问题标题】:Binding a BitmapImage obtained from a ByteStream to an ImageBrush on UWP C#将从 ByteStream 获得的 BitmapImage 绑定到 UWP C# 上的 ImageBrush
【发布时间】: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


【解决方案1】:

更改了图像源

ImageSource="{Binding Image}"

非常感谢克莱门斯!

【讨论】:

    【解决方案2】:

    使用

    ImageSource="{Binding Image}"
    

    而不是

    ImageSource="{x:Bind Image}"
    

    虽然x:Bind 需要精确的类型匹配,但Binding 利用了从多种源类型(例如stringUribyte[])到ImageSource 的内置转换。

    【讨论】:

    • 如果我想在项目模板之外访问此图像,我需要做些什么不同的事情吗?只说主要外部网格下的图像对象?
    • 不确定你的意思。如果您的视图模型中有 Image 属性,则绑定到它应该始终如下所示。
    猜你喜欢
    • 1970-01-01
    • 2016-02-02
    • 2014-05-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多