gpt4 book ai didi

uwp - 在 x :Bind and a IValueConverter? 中使用函数有什么区别

转载 作者:行者123 更新时间:2023-12-04 14:26:49 25 4
gpt4 key购买 nike

我在这两个 Functions in x:Bind 上都工作过(在 Windows 10 build 14393 中引入)和 IValueConverter将转换后的值绑定(bind)到 UI 元素的属性。但是,我想知道绑定(bind)值的正确或有效程序。使用它们有什么区别。

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

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
}
}

最佳答案

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

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


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

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

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

    关于uwp - 在 x :Bind and a IValueConverter? 中使用函数有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53796413/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com