2
votes
ListView listView = new ListView();
listView.ItemTemplate = new DataTemplate(typeof(CustomVeggieCell));
listView.ItemsSource = sample;
Content = new StackLayout
{
    Children ={
        listView,
    }
};


public class CustomVeggieCell : ViewCell
{
public CustomVeggieCell()
{
        var image = new Image();
        var typeLabel = new Label { };


        typeLabel.SetBinding(Label.TextProperty, new Binding("contact"));

        var string = typeLabel.Text;

        if (typeLabel.Text == "Send")
        {
            image.Source = "Send.png";
        }
        else
        {
            image.Source = "draft.png";
        }


        var horizontalLayout = new StackLayout();
        horizontalLayout.Children.Add(image);


        View = horizontalLayout;

    }
}

I have created a listview with Json Web service response in Xamarin forms. I need to display an image depending on the value. Binding value couldn’t store in a string. It always returns null. I want to store the binding label text. Ho to achieve this?

1

1 Answers

2
votes

You can use a IValueConverter

Something like

public class CustomVeggieCell : ViewCell
{
    public CustomVeggieCell()
    {
        var image = new Image();

        image.SetBinding(Image.SourceProperty, new Binding("contact", BindingMode.Default, new ConvertTextToSource()));

        var horizontalLayout = new StackLayout();
        horizontalLayout.Children.Add(image);


        View = horizontalLayout;

    }

}

Then the converter

        public class ConvertTextToSource : IValueConverter
        {

            #region IValueConverter implementation

            public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if ( value != null &&  value is string )  {

                    string text = ((string)value);

                    if (text == "Send")
                    {
                        return "Send.png";
                    }
                    else
                    {
                        return "draft.png";
                    }
                }
                return "";
            }

            public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException ();
            }

            #endregion
        }

It should works