首页 > 解决方案 > 使用图像或标签切换行为 -ON -OFF -在 xamarin 表单中的列表视图内绑定图像

问题描述

我想在被点击时将图像源从 white.png 更改为 blue.png ,当图像更改为 white.png 并且当它是 blue.png 时,我需要访问每个commannd ,这也将有助于根据图像结果设置它 true 或 false 。

所有这些都将出现在一个列表中。我需要访问每个被点击的人。

我试过了 :

值转换器

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}}"/>

这只会向我展示 else ,永远不会成真。理想情况下,我想访问它们中的每一个并为其添加逻辑,并且显然会更改每次点击时的图像。

第二种方法 - 这里的问题是 - 仅被点击一次,我无法在第二次点击时返回上一个图像,而且我不知道如何访问每个命令。(我想模仿一个开关,他们每个人都做一些事情)

public ImageSource ColorImage { get; set; }

查看模型

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"));
            }
        }

构造函数

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>

标签: imagexamlxamarin.formsdata-bindinginotifypropertychanged

解决方案


似乎 Image 在 listview 的 ViewCell 中。

您应该在模型中定义ColorImage

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";
    }
}

在您的视图模型中

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

   model.ColorImage = "imgcolorblue.png";

}

推荐阅读