【问题标题】:Bind XAML Image to IRandomAccessStreamReference将 XAML 图像绑定到 IRandomAccessStreamReference
【发布时间】:2016-10-03 10:40:48
【问题描述】:

Windows UWP C# API 使用 IRandomAccessStreamReference,虽然我可以获得如下的字节数组,但我无法使用我希望在 BitmapImage(来自 WPF)中找到的方法来生成位图图像;即使可以,我也觉得这个解决方案过于笨拙和乏味,无法成为预期的方法,而且它滥用了异步加载。

这在 UWP 中编译:

private static byte[] GetBytes(IRandomAccessStreamReference r)
{
    var stream = r.OpenReadAsync().GetResults();

    var bytes = new byte[stream.Size];
    stream.ReadAsync(bytes.AsBuffer(), (uint)stream.Size, InputStreamOptions.None).GetResults();

    return bytes;
}

由于 BeginInitCacheOptionBitmapCacheOptionStreamSourceEndInit 未定义,因此无法在 UWP 中编译:

public static BitmapImage ToImage(byte[] array)
{
    using (var ms = new System.IO.MemoryStream(array))
    {
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad; // here
        image.StreamSource = ms;
        image.EndInit();
        return image;
    }
}

我应该如何最好地使用 IRandomAccessStreamReference 来通过 UWP 显示图像?

我的具体用例是处理 Windows 联系人,我想为其构建一个集合并绑定到它;类似:

public void InitialiseSomeViewModel()
{
    var contactStore = ContactManager.RequestStoreAsync();
    contactStore.GetResults().FindContactsAsync().GetResults();

    ContactInfo = c.Select(x => new MyContactEntity { Name = x.Name, Thumbnail = x.Thumbnail});
}

请注意,此示例中的 ThumbnailIRansomAccessStreamReference

【问题讨论】:

    标签: c# xaml binding uwp


    【解决方案1】:

    我认为最好的方法是使用 InMemoryRandomAccessStreamIValueConverter 接口。因此,您可以解码执行运行时绑定的字节数组。

    首先您需要在 XAML 中的 Image Control 中指定 valueconverter。

    那么就可以使用下面的IValueConverter来解码字节数组了。

    class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null || !(value is byte[]))
                return null;
            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes((byte[])value);
                    writer.StoreAsync().GetResults();
                }
                var image = new BitmapImage();
                image.SetSource(ms);
    
                //other specification
    
                return image;
            }
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2017-01-29
      • 1970-01-01
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多