[英]Is it possible to create a Xamarin Converter dynamically and in one line?
Xamarin 转换器通常必须是 static(启动后未更改)和类,这使得它们在大多数情况下所做的事情相当大材小用。 因此我认为在运行时在一行中定义它们会更容易。
是的,如果您在调用InitializeComponent
之前创建对象,则可以使用包装器 class 。
这是一个示例包装器 class:
public class XamarinFormsConverter<TIn, TOut> : IValueConverter {
private readonly Func<TIn, TOut> _func;
public XamarinFormsConverter(Func<TIn, TOut> func) => _func = func;
public object Convert(object value, Type targetType, object _, CultureInfo __) {
if (targetType != typeof (TOut)) {
throw new Exception("Converter used with wrong targetType");
}
if (value is TIn val) {
return _func(val);
}
throw new Exception("Converter used with wrong inputType");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
以及如何使用它的示例:
public ResourceDictionary Converters { get; } = new ResourceDictionary {
["IsLoggedInToColor"] = new XamarinFormsConverter<bool, Color>(input => input ? Color.FromRgb(132, 255, 255) : Color.FromRgb(64, 196, 255)),
["IsLoggedInToView"] = new XamarinFormsConverter<bool, object>(input => input ? Views.User.ToString() : Views.Login.ToString()),
["BoolInvert"] = new XamarinFormsConverter<bool, bool>(input => !input),
["FromPercent"] = new XamarinFormsConverter<int, double>(input => (double)input / 100)
};
在初始化之前添加转换器很重要:
public MainPage() {
ViewModel = new ViewModel();
Resources.Add(ViewModel.Converters);
InitializeComponent();
BindingContext = ViewModel;
}
从技术上讲,也可以在初始化后更改转换器的行为,但名称和对象必须在此之前创建。
我希望有些人可以使用它来使他们的代码更简单和更具可读性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.