Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference in using Functions in x:Bind and a IValueConverter?

I have worked on both Functions in x:Bind (which is introduced in windows 10 build 14393) and IValueConverter to bind converted values to a property of an UI element. But, I would like to know which is right or efficient procedure to bind the values. What’s the difference in using them.

Example : You can use both Functions in x:Bind and IValueConverter to bind a string to ‘calendardatepicker’. But, which is efficient one?

1.Functions in x:Bind

//Xaml

 <CalendarDatePicker Date="{x:Bind ConvertStringToDate(Date),Mode=OneWay}"></CalendarDatePicker>

//C#

 public DateTimeOffset ConvertStringToDate(string date)
   {
      DateTime d;
      d = System.Convert.ToDateTime(date);
      d = DateTime.SpecifyKind(d, DateTimeKind.Local);
      return (DateTimeOffset)d;
   }

2.Using IValueConverter

//Xaml

<CalendarDatePicker Date="{x:Bind Date,Converter={StaticResource StringtoDate},Mode=OneWay}"></CalendarDatePicker>

//C#

 public class DateToStringConverter : IValueConverter
 {
    public object Convert(object value, Type targetType,
              object parameter, string language)
    {
        DateTime d = DateTime.Now;
        string date = (string)value;
        d = System.Convert.ToDateTime(date);
        d = DateTime.SpecifyKind(d, DateTimeKind.Local);
        return (DateTimeOffset)d;
    }
    public object ConvertBack(object value, Type targetType,
            object parameter, string language)
    {
            //blah blah
    }
}
like image 844
Vignesh Avatar asked Mar 04 '23 21:03

Vignesh


1 Answers

The actual difference is in number of parameter and ease of use, as said in the doc:

  • A simpler way to achieve value conversion
  • A way for bindings to depend on more than one parameter

And from the comment of Raymond Chen:

  • Functions are resolved at compile time, which benefits both correctness (you get a compile-time error if you get the data type wrong) and performance (don't have to keep boxing and unboxing). Converters are looked up at runtime, so you don't learn that you did it wrong you load the page and get a runtime exception. But sometimes the loose typing is handy.

and I think it's much easier to just have a function with the bonus of the capability of using multiple parameters instead of implementing an interface.

you see, you can just say x:Bind ConvertStringToDate(Date)in x:Bind which is much easier and nifty way to convert values than IValueConverter

like image 165
Muzib Avatar answered May 12 '23 05:05

Muzib