Achiel Volckaert
Achiel Volckaert

Reputation: 1014

How to modify binded value in MVVM Cross

I have a model from my json in a Xamarin MVVM app(ios). I want to add the "%" after the value? in the list "coinmarketcaplist" contains the value 24h_change, this is the value I want to add a % to, it's a string. I know that I should use a getter for it, but I don't know how since I'm fairly new to this. below is my ViewModel code:

public class CMCTableViewModel : MvxViewModel
{
    protected readonly ICoinMarketCapService _coinMarketCapService;
    public CMCTableViewModel(ICoinMarketCapService coinMarketCapService)
    {
        _coinMarketCapService = coinMarketCapService;
        LoadData();
    }

    private List<CoinMarketCapModel> _coinMarketCapModelList;
    public List<CoinMarketCapModel> CoinMarketCapModelList
    {
        get
        {

            return _coinMarketCapModelList;
        }
        set
        {
            _coinMarketCapModelList = value;
            RaisePropertyChanged(() => CoinMarketCapModelList);
        }
    }

    public async void LoadData()
    {
        CoinMarketCapModelList = await _coinMarketCapService.GetCoins();
    }
}

TableCell:

internal static readonly NSString Identifier = new NSString("CMCTableCell");

  public override void LayoutSubviews()
  {
    base.LayoutSubviews();
    MvxFluentBindingDescriptionSet<CMCTableCell, CoinMarketCapModel> set = new MvxFluentBindingDescriptionSet<CMCTableCell, CoinMarketCapModel>(this);
    set.Bind(lblName).To(res => res.Name);
    set.Bind(lblPrice).To(res => res.percent_change_24h);
    set.Bind(imgCoin)
     .For(img => img.Image)
     .To(res => res.image)
     .WithConversion<StringToImageConverter>();
    set.Apply();
  }
}

edit: added cellview

Upvotes: 1

Views: 90

Answers (1)

Michał Żołnieruk
Michał Żołnieruk

Reputation: 2105

Use a converter in your binding:

1) Define converter:

public class StringFormatValueConverter : MvxValueConverter
{
    public override object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value;

        return string.Format(parameter.ToString(), value);
    }
}

2) Use it in your binding:

set.Bind(lblPrice).To(res => res.percent_change_24h).WithConversion<StringFormatValueConverter>("{0} %");

You can use this converter when you want to modify the input string by adding something around it, for example unit or currency

Upvotes: 3

Related Questions