To solve this scenario, you can implement an Ivalueconverter, which will be responsible for validating and displaying your image according to the desired rule, and displaying the images according to the rules.
In this example I created I implemented a simple project, where the rule is based on the name that comes from Binding, plus, you are free to implement the rule as you wish.
Follows the code:
Arquivo Convertervalue
using System;
using System.Globalization;
using Xamarin.Forms;
namespace XFlImageButtonListView.Converter
{
/// <summary>
/// Método responsável em Exibir icone no botão, através de uma regra de negócio
/// </summary>
public class ImageViewConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
//Valida regra de negócio para exibir imagem no botão
if(value.ToString().Equals("Nome1"))
//Exibe imagem para cada platforma.
return Device.OnPlatform<String>("callanswerIOS.png", "callanswer.png", "img/callanswerUWP.png");
else
//Exibe imagem para cada platforma.
return Device.OnPlatform<String>("pointingdownIOS.png", "pointingdown.png", "img/pointingdownUWP.png");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
//Volta a imagem padrão para cada platforma.
return Device.OnPlatform<String>("pointingdownIOS.png", "pointingdown.png", "img/pointingdownUWP.png");
}
}
}
XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:XFlImageButtonListView"
xmlns:converter="clr-namespace:XFlImageButtonListView.Converter"
x:Class="XFlImageButtonListView.MainPage">
<ContentPage.Resources>
<ResourceDictionary>
<converter:ImageViewConverter x:Key="imgConvert"></converter:ImageViewConverter>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<StackLayout VerticalOptions="Center" Spacing="50">
<ListView x:Name="lstPalestrantes"
ItemsSource="{Binding Palestrantes}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Button Text="{Binding Nome}" Image="{Binding Nome, Converter={StaticResource imgConvert}}" BackgroundColor="Transparent" />
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
I created a solution on github for this, if you want to know more details:
https://github.com/juniorporfirio/XFlImageButtonListView
I hope I’ve helped.
Doubts, I’m at your disposal.
The image
editar.png
(specifically Android) is in the appropriate folder? https://developer.xamarin.com/guides/android/application_fundamentals/resources_in_android/part_1_-_android_resource_basics/. Sometimes it is necessaryclean
,rebuild
in the project.– rubStackOverflow
@rubStackOverflow is yes, I’ve given clean and rebuild several times and it doesn’t work.
– AndreeH