在 x:Bind 和 IValueConverter 中使用函数有什么区别?

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

我已经完成了两个 Functions in x:Bind (which is introduced in windows 10 build 14393) and IValueConverter 的工作,将转换后的值绑定到 UI 元素的 属性。但是,我想知道绑定值的正确或有效程序。使用起来有什么区别

示例:您可以使用 x:Bind 中的函数和 IValueConverter 将字符串绑定到“calendardatepicker”。但是,哪个有效呢?

1.Functions 在 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
    }
}

实际的区别在于参数的数量和易用性,如the doc中所述:

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

以及来自Raymond Chen的评论:

  • 函数在编译时解析,这对正确性(如果数据类型错误会出现编译时错误)和性能(不必保持装箱和拆箱)都有好处。转换器在运行时被查找,所以你不会知道你做错了加载页面并获得运行时异常。但有时松散的打字很方便。

而且我认为只拥有一个具有使用多个参数的功能而不是实现接口的功能要容易得多。

你看,你可以在 x:Bind 中说 x:Bind ConvertStringToDate(Date) 这比 IValueConverter

更容易和巧妙地转换值