Xamarin从byte []数组中形成ListView图像

时间:2017-02-17 15:31:50

标签: xamarin xamarin.forms

我很难将ListView图像绑定到byte []数组。该列表正在拾取它应该的2条记录,但图像没有显示出来。我使用的是MVVM模式。

XAML:

<ContentPage.Resources>
    <ResourceDictionary>
        <local:ByteArrayToImageSourceConverter x:Key="ByteArrayToImage" />
    </ResourceDictionary>
</ContentPage.Resources>

<ScrollView>
<ListView ItemsSource="{Binding Pictures}" ItemTapped="ItemTapped" IsPullToRefreshEnabled="true" RefreshCommand="{Binding   RefreshPicturesCommand}" IsRefreshing="{Binding IsBusy, Mode=OneWay}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Image Source="{Binding ImageBytes, Converter={StaticResource ByteArrayToImage}}"></Image> 
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

型号:

public class Picture
{
    public string Name { get; set; }
    public byte[] ImageBytes { get; set; }
}

转换器:

public class ByteArrayToImageSourceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        ImageSource retSource = null;
        if (value != null)
        {
            byte[] imageAsBytes = (byte[])value;
            var stream = new MemoryStream(imageAsBytes);
            retSource = ImageSource.FromStream(() => stream);
        }
        return retSource;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

ViewModel字段:

ObservableRangeCollection<Picture> _Pictures;
public ObservableRangeCollection<Picture> Pictures
    {
        get { return _Pictures ?? (_Pictures = new ObservableRangeCollection<Picture>()); }
        set
        {
            _Pictures = value;
            OnPropertyChanged("Pictures");
        }
    }

ViewModel GetPictures方法的相关部分:

var bytes = await PCLHelper.LoadImage(file.Name, contentFolder);

                    Picture pic = new Picture
                    {
                        Name = file.Name,
                        ImageBytes = bytes
                    };

                    Pictures.Add(pic);

绑定正在运行,因为如果我添加标签,它将显示文件的名称。非常感谢任何帮助。

克里斯

0 个答案:

没有答案