将base64字符串绑定到xamarin形式的listview

时间:2016-09-03 10:14:55

标签: c# windows xaml xamarin.forms

首先,我是Xamarin.Form的新手。我正试图从谷歌中获得最佳效果,但我甚至无法获得一些功能。

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

我的问题是,如何将base64 string转换为图像,并将图像绑定到列表视图。

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)
    {

    }          
}

所以任何人请建议我一个想法和任何解决方案。

1 个答案:

答案 0 :(得分:4)

根据this论坛帖子,您可以为其创建转换器。 只需将Base64字符串保留为Employee的一部分,即Base64Image属性。

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

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声明并使用这样的转换器:

将命名空间添加到页面根目录,我将假设它是正常的ContentPage,因此它应该类似于:

<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等应替换为您的实际应用名称和正确的命名空间。

现在声明转换器是您网页的一部分。

<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>

现在应该显示您的图片了!