Forum Xamarin.Forms

How do I use IValueConverters?

CheesebaronCheesebaron DKInsider, University mod

I have created a converter which looks like this:

public class SecondsToHoursMinutesValueConverter 
    : IValueConverter
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        var t = TimeSpan.FromSeconds((int)value);

        return string.Format("{0:D2} hours {1:D2} minutes", t.Hours, t.Minutes);

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

Now I want to bind it with:

runtime.SetBinding(Label.TextProperty, new Binding("Runtime"), BindingMode.Default,
    new SecondsToHoursMinutesValueConverter(), null);

However, VS does not like it and says there is an error in that code:

Error 1 The type arguments for method 'Xamarin.Forms.BindableObjectExtensions.SetBinding(Xamarin.Forms.BindableObject, Xamarin.Forms.BindableProperty, System.Linq.Expressions.Expression<System.Func<TSource,object>>, Xamarin.Forms.BindingMode, Xamarin.Forms.IValueConverter, string)' cannot be inferred from the usage. Try specifying the type arguments explicitly. D:\git\Xam.Forms.Mvx\CoolBeans\CoolBeans\Pages\DetailedMoviePage.cs 101 13 CoolBeans


  • CheesebaronCheesebaron DKInsider, University mod

    Yeah, but I don't use XAML.

  • CheesebaronCheesebaron DKInsider, University mod

    That seems to do the trick. What is the IValueConverter argument in SetBinding for then, when is that used?

  • rmarinhormarinho PTMember, Insider, Beta Xamurai

    Good question @Cheesebaron‌ , don't know either. Maybe @StephaneDelcroix‌ or @JasonASmith‌ could answer that one.

  • rmarinhormarinho PTMember, Insider, Beta Xamurai

    thanks :)

  • NamHoang.3859NamHoang.3859 CAMember ✭✭

    How do you provide the parameter "Expression<Func<TSource, object>> sourceProperty"

    I have this piece of code:

        var address = new Address();
        var entry = new Entry 
                        BindingContext = address

    I want to bind the entry text to address.State.

    I know I can do something like this:

        entry.SetBinding(Entry.TextProperty, "State", BindingMode.TwoWay);

    However, if I refactor the property "State" to "Province" for example, I have to go change the string instead of using the Rename feature of Visual Studio / Xamarin Studio. Therefore, I would like to use the Expression if it can solve the refactoring problem.

    Thank you very much.

  • NamHoang.3859NamHoang.3859 CAMember ✭✭

    Never mind,

    I figured it out, it will be

            entry.SetBinding<Address>(Entry.TextProperty, x => x.State, BindingMode.TwoWay)
  • @rmarinho Would it also be possible to bind to an IValueConverter in the BindingContext instead of using StaticResource? Like this?

    <Grid VerticalOptions="End" HorizontalOptions="Center" IsVisible="{Binding IsVisible, Converter={Binding cnvInvert}}">

    I tried doing this, but I get the following error when I try binding in XAML, but it works when I setup up the binding in the code behind.

    System.Exception: A Binding Converter must be of type IValueConverter.

  • rmarinhormarinho PTMember, Insider, Beta Xamurai

    No, that's not possible. Converter is not bindable, AND you can't change a binding

  • SachinAgrawalSachinAgrawal USUniversity ✭✭

    @Cheesebaron Hi, I am trying to implement Input validation in Xamarin.Forms using Behaviors. I am not using XAML. I want to do this in code behind. I have most of it working except this - I have seen a sample where when a user starts typing a number in the Entry and a label below the entry appears in "green" if the number is valid, but if not then the label becomes red. Any suggestions? Thanks

  • PierreSavardPierreSavard CAMember ✭✭

    Sorry for hijacking this old post! Maybe I do not do it correctly. When I use {Binding .} I got in my converter the ViewModel directly. But what I need is the object of the collection bound to the listview.
    For example, I got an observableCollection of Calls. In that collection I got 2 field DateStart, DateEnd.
    In my listview I need a column that need to use theses 2 dates calculate something and return a string. So my "root" need the Call object in the Calls collection currently being drawn instead of the whole viewModel I got with {Binding .}. Do we have a way to do that?

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    @PierreSavard I think a solution can be to create a new Property in your Model that return the string to visualize in the ListView

Sign In or Register to comment.