将 base64 字符串绑定到 xamarin 形式的列表视图 [英] Bind base64 string to listview in xamarin form

查看:14
本文介绍了将 base64 字符串绑定到 xamarin 形式的列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是 Xamarin.Form 的新手.我正在努力从 Google 获得最佳效果,但有些功能我什至无法进行大量搜索.

First of all I am new in Xamarin.Form. I am trying to get best from Google but some of functionality I am not able to get even searched a lot.

我正在创建 Xamarin.Form 应用程序.在该应用程序中,我将图像存储为 sql server 中的 base64 string 格式,我在 sql server 中的数据类型是 varchar(Max).

I am creating a Xamarin.Form app. In that app, I am storing the image to base64 string format in sql server and my data type in sql server is varchar(Max).

我的问题是,如何将 base64 字符串 转换为图像并将图像绑定到列表视图.

My issue is that, How can I convert the base64 string to an image and also with bind the image to list view.

Listview 代码:

Code of Listview:

<ListView x:Name="listView" HasUnevenRows="true" SeparatorColor="Gray">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Image Source="{Binding image}"  Grid.Row="0" 
                        Grid.RowSpan="3" Grid.Column="0" 
                        HorizontalOptions="Center" HeightRequest="50" 
                        VerticalOptions="Center">
                    <Image.GestureRecognizers>
                        <TapGestureRecognizer Tapped="OnImageTapped" />
                    </Image.GestureRecognizers>
                </Image>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

c#代码:

Public async Task loadDeveloperList()
{
    try
    {            
        List<employee> employeeDetail = new List<employee>();

        HttpClient client = new HttpClient();
        StringBuilder sb = new StringBuilder();
        client.MaxResponseContentBufferSize = 256000;
        var RestUrl = "http://example.com/Getemployee/";
        var uri = new Uri(RestUrl);
        actIndicator.IsVisible = true;
        actIndicator.IsRunning = true;
        var response = await client.GetAsync(uri);

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();

            List<employee> onjEmployee = JsonConvert.DeserializeObject<List<employee>>(content);

            foreach (var item in onjEmployee)
            {
                employee emptemp = new employee()
                {
                    empID = item.empID,
                    name = item.name,
                    city = item.city,
                    post = item.post,
                    salary = item.salary,
                    gender = item.gender,
                    image = item.image                            
                };
                string cFotoBase64 = emptemp.image;
                byte[] ImageFotoBase64 = System.Convert.FromBase64String(cFotoBase64);

                employeeDetail.Add(emptemp);                                         
            }
            listView.ItemsSource = employeeDetail;
        }
    }
    catch (Exception ex)
    {

    }          
}

所以任何人都请给我一个想法和任何解决方案.

So any one please suggest me a idea and any solution.

推荐答案

根据 this 论坛主题,您可以为它创建一个转换器.只需将 Base64 字符串保留为 Employee 的一部分,即在 Base64Image 属性中.

As per this forum thread you could create a converter for it. Just keep the Base64 string as part of your Employee i.e. in the Base64Image property.

现在定义一个这样的转换器.

Now define a converter like this.

public class ConverterBase64ImageSource : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
    {
        string base64Image = (string)value;

        if (base64Image == null)
            return null;

        // Convert base64Image from string to byte-array
        var imageBytes = System.Convert.FromBase64String(base64Image);

        // Return a new ImageSource
        return ImageSource.FromStream (() => {return new MemoryStream(imageBytes);});
    }

    public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Not implemented as we do not convert back
        throw new NotSupportedException();
    }
}

现在在您的 XAML 中声明并使用转换器,如下所示:

Now in your XAML declare and use the converter like this:

将命名空间添加到页面根目录,我假设它是一个普通的ContentPage,所以它应该看起来像:

Add the namespace to the page root, I'm going to assume it's a normal ContentPage, so it should look something like:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:YourApp;assembly=YourApp"
             x:Class="YourApp.YourPage">

请注意,YourAppYourPage 等应替换为您的实际应用名称和正确的命名空间.

Note that YourApp and YourPage, etc. should be replaced with your actual app name and the right namespaces.

现在将转换器声明为页面的一部分.

Now declare the converter as part of your page.

<ContentPage.Resources>
   <ResourceDictionary>
      <local:ConverterBase64ImageSource x:Key="Base64ToImageConverter" />
   </ResourceDictionary>
</ContentPage.Resources>

最后在Image上使用转换器.

<ListView x:Name="listView" HasUnevenRows="true" SeparatorColor="Gray">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Image Source="{Binding Base64Image, Converter={StaticResource Base64ToImageConverter}}}"  Grid.Row="0" 
                        Grid.RowSpan="3" Grid.Column="0" 
                        HorizontalOptions="Center" HeightRequest="50" 
                        VerticalOptions="Center">
                    <Image.GestureRecognizers>
                        <TapGestureRecognizer Tapped="OnImageTapped" />
                    </Image.GestureRecognizers>
                </Image>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

现在应该显示您的图像!

Your images should now be shown!

这篇关于将 base64 字符串绑定到 xamarin 形式的列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆