简体   繁体   English

绑定来自SQLite数据库,Xamarin表单的ListView图像

[英]Binding ListView Images from SQLite database, Xamarin forms

I have a Person model: 我有一个Person模型:

 public class Person
 {
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public string FirstName{ get; set; }
    public string LastName{ get; set; }
    public byte[] Image { get; set; }
 }

In my SQLite database I have pictures stored in the table. 在我的SQLite数据库中,表中存储了图片。 I'm trying to show the images in a ListView. 我正在尝试在ListView中显示图像。 So implemented a ImageConverter: 因此实现了一个ImageConverter:

  public class ImageConverter : 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();
    }

}

In the Xaml code I'm trying to bind och convert the image like this: 在Xaml代码中,我试图绑定och转换图像,如下所示:

<Page.Resources>
    <converters:ImageConverter x:Key="ImageConverter" />
</Page.Resources>
<ContentPage.Content>
    <ListView x:Name="PersonListView">

        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell Height="220">
                  <Image Source="{Binding Image, Converter={StaticResource ImageConverter}}"/>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage.Content>

When I run the page I get this error: 当我运行页面时,出现此错误:

System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException:对象引用未设置为对象的实例。

I don't understand where it's wrong in my code. 我不明白我的代码在哪里出了问题。 How can I view pictures from my database? 如何查看数据库中的图片?

Try this code in your converter and let me know it works or not: 在您的转换器中尝试以下代码,让我知道它是否有效:

public class ImageConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {                        
        return "data:image;base64," + Convert.ToBase64String(value);;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo     culture)
    {
        throw new NotImplementedException();
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM