Xamarin 轉換器通常必須是靜態的(啟動后不更改)和類,這使得它們在大多數情況下的作業都顯得過于矯枉過正。因此,我認為在運行時在單行中定義它們會更容易。
uj5u.com熱心網友回復:
是的,可以使用包裝類,并且如果您在呼叫之前創建物件InitializeComponent。
這是一個示例包裝類:
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;
}
從技術上講,也可以在初始化后更改轉換器的行為,但必須先創建名稱和物件。
我希望有些人可以使用它來使他們的代碼更簡單、更易讀。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/445081.html
標籤:C# xamarin xamarin.forms 价值转换器
