Pxaml
Pxaml

Reputation: 555

Switch behavior -ON -OFF using an Image or label -Binding an image inside a listview in xamarin forms

I would like to change the image source from white.png to blue.png when it gets tapped , I need to access each comannd when the image schange to white.png and when it is blue.png , also .it will be helpful to set it true or false , depending on the image result.

all this will come inside a list . and I need to access each individual tapped.

I tried :

IValueConveter

public class ConverterAddRemoveImage : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            bool isAddedToCart = (bool)value;
            if (isAddedToCart)
            {
                return "FilledIcon"; //This will be a string
            }
            else
            {
                return "EmptyIcon";  //This will be a string
            }
        }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

Xaml

<Image Source="{Binding IsAddedToCart, Converter={StaticResource AddRemoveImage}}"/>

This only shows me the else , never gets to true. Ideally I would like to access each of them and add logic to it and obviously change the image on each tapped.

Second approach- the issue here is - gets tapped only one time and I can not get back to the previous image with the second tapped , and also , I dont know how to access each command. (I want to imitate a switch on and off and on each of them do something)

public ImageSource ColorImage { get; set; }

View Model

public ICommand SwitchIMGCommand
            {
                get;
                set;
            }



private void AddImg(object obj)
  {
     var selection = obj as ExistingModel;
     selection.ColorImage = "FilledIcon.png";**
     ColorImage= "FilledIcon.png";**I tried this and it doesnt change 
     to this img
  }



private ImageSource imagePath = "white.png";
        public ImageSource ColorImage
        {
            get { return imagePath; }
            set
            {
                imagePath = value;
                PropertyChanged(this, new PropertyChangedEventArgs("ColorImage"));
            }
        }

Constructor

SwitchIMGCommand = new Command(AddImg);

XAML

<Image
    Source="{Binding ColorImage}">  
    <Image.GestureRecognizers>
    <TapGestureRecognizer
    Command="{Binding Source={x:Reference listView}, Path=BindingContext.SwitchIMGCommand}" CommandParameter="{Binding .} "
     NumberOfTapsRequired="1" />
     </Image.GestureRecognizers>
  </Image>

Upvotes: 1

Views: 599

Answers (4)

Ben
Ben

Reputation: 2995

XAML using DataTrigger - ChangeIsCheckedCommand changes the IsChecked property:

<Image>
  <Image.GestureRecognizers>
    <TapGestureRecognizer Command="{Binding ChangeIsCheckedCommand}" NumberOfTapsRequired="1" />
  </Image.GestureRecognizers>
  <Image.Triggers>
    <DataTrigger TargetType="Image" Binding="{Binding IsChecked}" Value="True">
      <Setter Property="Source" Value="{StaticResource OnImage}" />
    </DataTrigger>
    <DataTrigger TargetType="Image" Binding="{Binding IsChecked}" Value="False">
      <Setter Property="Source" Value="{StaticResource OffImage}" />
    </DataTrigger>
  </Image.Triggers>
</Image>

Resources for OnImage and OffImage:

<OnPlatform x:Key="OnImage" x:TypeArguments="FileImageSource">
  <On Platform="Android">on.png</On>
  <On Platform="iOS">on.png</On>
  <On Platform="UWP">Assets/on.png</On>
</OnPlatform>

<OnPlatform x:Key="OffImage" x:TypeArguments="FileImageSource">
  <On Platform="Android">off.png</On>
  <On Platform="iOS">off.png</On>
  <On Platform="UWP">Assets/off.png</On>
</OnPlatform>

Upvotes: 1

Ricardo Dias Morais
Ricardo Dias Morais

Reputation: 2087

This a complement to Lucas Zhang Anwser, wich is the correct way to do it but it misses the toggle Funtionality to convert back to the original form.

Here is what missing:

1º - Add a bool property to the Model

private bool _isCheckedState;
public bool IsCheckedState
{
    get { return _isCheckedState; }
    set
    {
        _isCheckedState= value;
        NotifyPropertyChanged("IsCheckedState");
    }
}

2º - Add a verification before setting the ColorImage

private void AddImg(object obj)
{
    var model = obj as MyModel;

    if(model.IsCheckedState)
        model.ColorImage = "white.png";
    else
        model.ColorImage = "imgcolorblue.png";

    model.IsCheckedState = !model.IsCheckedState;
}

Upvotes: 0

Lucas Zhang
Lucas Zhang

Reputation: 18861

It seems that the the Image is in the ViewCell of a listview .

You should define the ColorImage in your model .

public class MyModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;


    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string imagePath;
    public string ColorImage
    {
        get { return imagePath; }
        set
        {
            imagePath = value;
            NotifyPropertyChanged("ColorImage");
        }
    }


    //...other properties     

    public MyModel()
    {
       ColorImage = "white.png";
    }
}

in your view model

private void AddImg(object obj)
{
   var model = obj as MyModel;

   model.ColorImage = "imgcolorblue.png";

}

Upvotes: 2

BasisPrune
BasisPrune

Reputation: 94

You are using the wrong type for your parameter "ColorImage". The source of an image is ImageSource type.

Assuming you set your images correctly on your project, the following code should solve your issue

private void AddImg(object obj)
{
    ColorImage = ImageSource.FromFile("imgcolorblue.png");
}

Change also the type of "ColorImage" by ImageSource.

Upvotes: -1

Related Questions