1
votes

I am new with xamarin, I am facing an issue in my xamarin forms project. I have two images inside listview-viewcell, one is for showing like and other for unlike. If the value of isUserLiked is true show the second image and otherwise show the first one. I try with !, but not working. Here is my code:

   <StackLayout HeightRequest="500">
        <ListView x:Name="ListView1" RowHeight="500" HorizontalOptions="CenterAndExpand">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout
                            Orientation="Vertical">
                                <Image
                                    Source="unlike.png"
                                    IsVisible="{Binding !isUserLiked}"> 
                                </Image>
                                <Image
                                    Source="like.png"
                                    IsVisible="{Binding isUserLiked}">                                      
                                </Image>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>           
    </StackLayout>

How to reverse the binding value inside listview-viewcell. Anybody please suggest a solution with working code. Thanks in advance.

2

2 Answers

1
votes

You can't use operator in binding. Best way to use trigger for that like this :

<Image Source="unlike.png"> 
    <Image.Triggers>
        <DataTrigger TargetType="Image" Binding="{Binding isUserLiked}" Value="True">
            <Setter Property="Source" Value="like.png" />
        </DataTrigger>
    </Image.Triggers>
</Image>

Or

Another way to use converter like this:

Converter

public class InverseBoolConverter : IValueConverter, IMarkupExtension
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !((bool)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
            //throw new NotImplementedException();
        }


        public object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }
    }

Now you can use in your Xaml code like this :

<Image Source="unlike.png" IsVisible="{Binding isUserLiked, Converter={Helpers:InverseBoolConverter}}" />

Don't forgot to add assembly in xaml header :

xmlns:Helpers="clr-namespace:MyNameSpace.Helpers"

0
votes

You could either work around it by creating another property in your ViewModel which gives you the inverse value.

A better way would be to use a ValueConverter, I have written a blog about it here. In the converter you could inverse the boolean value.

However there are also libraries that do that for you, they basically implement this converter for you.