【问题标题】:Whats the difference in using Functions in x:Bind and a IValueConverter?在 x:Bind 和 IValueConverter 中使用函数有什么区别?
【发布时间】:2019-05-16 17:01:54
【问题描述】:

我在 Functions in x:Bind(在 Windows 10 内部版本 14393 中引入)和 IValueConverter 都致力于将转换后的值绑定到 UI 元素的属性。但是,我想知道绑定值的正确或有效程序。使用它们有什么区别。

示例:您可以使用 x:Bind 和 IValueConverter 中的两个函数将字符串绑定到“日历选择器”。但是,哪个效率更高?

1.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.使用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
    }
}

【问题讨论】:

标签: uwp windows-10-universal uwp-xaml


【解决方案1】:

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

  • 更简单的实现价值转换的方法
  • 一种绑定依赖多个参数的方法

还有来自Raymond Chen的评论:

  • 函数在编译时解析,这有利于正确性(如果数据类型错误,则会出现编译时错误)和性能(不必继续装箱和拆箱)。转换器是在运行时查找的,因此您不会知道您做错了加载页面并获得运行时异常。但有时松散的打字很方便。

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

你看,你可以说x:Bind ConvertStringToDate(Date)in x:Bind,这比IValueConverter更容易和漂亮的转换值的方法

【讨论】:

  • 函数在编译时解析,这有利于正确性(如果数据类型错误,则会出现编译时错误)和性能(不必继续装箱和拆箱)。转换器是在运行时查找的,因此您不会知道您做错了加载页面并获得运行时异常。但有时松散的打字很方便。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
  • 2018-03-07
  • 2020-11-27
  • 2021-10-24
  • 2013-03-30
相关资源
最近更新 更多