xamarin 中的 UxBoolConvert

UxBoolConvert in xamarin

我正在做一个购物车应用程序,我需要更改 addToCart 按钮中的图像 当我将一个项目添加到购物车时,我在列表视图中有“+”按钮,图像必须更改为“-”。当我从我的购物车中删除一个项目时,图像再次变为“+”。我希望在这里我也需要通知但如何在这里实施。我现在有一个布尔值 属性。我的逻辑是这样 "change the Boolean value while adding and removing but i don't know how to change the image to the button" 这是我的视图模型

public BaseViewModel(){
        App.Instance.ViewModel = this;
        TempList = TempList ?? new ObservableCollection<cm_items>();
        this.Title = AppResources.AppResource.Cart_menu_title;
        this.IsContain = CartCell.buttonImg();
        TempList.CollectionChanged += (sender, args) =>{
            this.Price = CartCell.Calculate_price();};}

和我的属性

  private bool _isContain;
    public bool IsContain
    {
        get { return _isContain; }
        set {_isContain=value;OnPropertyChanged("IsContain");}
    }

和转换器

 public class BoolToImageConverter : IValueConverter
{
      #region IValueConverter implementation

    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is bool)  {

            if((bool)value == true)
    return "add.png";
    else
    return "minus.png";
        }
        return "";
    }

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

    #endregion
}

但我的按钮中仍然没有图像

您应该绑定这些属性,而不仅仅是分配它们:https://developer.xamarin.com/guides/cross-platform/xamarin-forms/user-interface/xaml-basics/data_binding_basics/

yourImageView.SetBinding<YourViewModelType>(Image.SourceProperty, v => v.IsContain);

并记住将页面 BindingContext 设置为您的 ViewModel 实例。

为什么不使用 ValueConvertor 而不是只使用将按钮的图像 属性 绑定到的图像 属性。

将一组示例代码放在一起,如下所示。

IE

public class MyPage : ContentPage
    {
        ObservableCollection<string> listToWatch = new ObservableCollection<string> ();
        public MyPage ()
        {
            Button buttonToUpdate = new Button {Text = "Image Button",  Image = "icon.png"};
            Button UpdatesList = new Button {Text="Add Item to list"};
            buttonToUpdate.SetBinding (Button.ImageProperty, new Binding("ImagePath"));
            UpdatesList.Clicked += (sender,e) => {
                listToWatch.Add (DateTime.Now.ToString());
            };
            listToWatch.CollectionChanged+=(sender,e)=>{
                if( listToWatch.Count%2==1)
                {
                    ImagePath="noci.png";       
                }
                else
                {
                    ImagePath="icon.png";
                }
            };
            Content = new StackLayout { 
                Children = {
                    buttonToUpdate,
                    UpdatesList
                }
            };
            Content.BindingContext = this;
        }
        private string imagePath="icon.png";
        public string ImagePath {
            get { return imagePath; } 
            set { 
            imagePath = value; 
            OnPropertyChanged ("ImagePath");
            }
        }
    }

我把完整的应用扔到 https://github.com/DavidStrickland0/Xamarin-Forms-Samples.git

ViewModel 看起来不错。你能提供你的按钮吗?如何将 IsContain 属性 绑定到按钮的图像 属性?

在你那里我会创建一个稍微不同的转换器:

    public class UxBoolConvertExtension : IValueConverter, IMarkupExtension
{
    public object OnTrue { get; set; }

    public object OnFalse { get; set; }

    public object OnNull { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ImageSourceHelper.ToImageSourceIfPossible(this.ConvertValue(value), targetType);
    }

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

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

    private object ConvertValue(object value)
    {
        if (value == null) return this.OnNull;
        return (bool)value ? this.OnTrue : this.OnFalse;
    }
}

并且会使用像

这样的转换器将按钮图像绑定到您的值上
<Button Image="{Binding Icon, Converter={m:UxBoolConvert OnTrue='minus.png', OnFalse='add.png'}}" />

在我的视图单元格中

  var addedOrNotImageBinding = new Binding("IsAddedToCart", 0, new ImagePathConvertor());
        btn_Cart.SetBinding(ImageButton.SourceProperty,addedOrNotImageBinding);

        btn_Cart.Clicked += (sender, e ) =>
            {
                sender = BindingContext;

                cm_items item = (cm_items)sender;
                //ViewCell viewCell = (ViewCell)sender;
                //BaseViewModel item = (BaseViewModel)viewCell.BindingContext;
                if (item.IsAddedToCart)
                {

                   item.IsAddedToCart = false;
                    App.Instance.ViewModel.TempList.Remove(BindingContext as cm_items);
                }
                else
                {
                    item.IsAddedToCart = true;
                    App.Instance.ViewModel.TempList.Add(BindingContext as cm_items);
                }

             //   CartCell.Calculate_price();
            };

并且必须添加一个名为 ImagePathConvertor 的 class 用于转换图像

public class ImagePathConvertor : IValueConverter
{
    public ImagePathConvertor() { }



    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if ((bool)value)
        {
            return "minus";
        }
        else
        {
            return "add";
        }


    }

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

    #endregion
}

在我的模型中

   private bool isAddedToCart;
    public bool IsAddedToCart
    {
        get { return isAddedToCart; }
        set
        {
            isAddedToCart = value;
            OnPropertyChanged("IsAddedToCart");
        }
    }
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

它对我来说很好用图片正在改变谢谢@David